When you use C# for programming in Function Compute, you must define a C# function as the handler function. After you configure an HTTP trigger for a function, the function can directly process HTTP requests, which facilitates the creation of web applications.

Background information

If you use C# to write HTTP functions in Function Compute, you must import Aliyun.Serverless.Core and Aliyun.Serverless.Core.Http packages through NuGet.

The following example shows the definition of a simple C# HTTP function:

using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Aliyun.Serverless.Core;
using Aliyun.Serverless.Core.Http;

namespace MySpace.TestHandlers
{
    public class SingleHttpHandler : FcHttpEntrypoint
    {
        protected override void Init(IWebHostBuilder builder)
        { }


        public override async Task<HttpResponse> HandleRequest(HttpRequest request, HttpResponse response, IFcContext fcContext)
        {
            response.StatusCode = 200;
            response.ContentType = "text/plain";

            await response.WriteAsync("hello world");

            return response;
        }
    }
}         

Input parameters of the function are as follows:

Note C# HTTP functions must inherit FcHttpEntrypoint from Aliyun.Serverless.Core.Http. You must rewrite the Init function and can determine whether to rewrite HandleRequest, which is the handler function of the function.
  • For single functions, you must rewrite HandleRequest. HandleRequest allows you to write the function according to your business logic.

  • For ASP.NET Core applications, you must rewrite the Init function only.

Example of HTTP functions

  • Example of a single function

    The following example shows how to use HttpRequest and HttpResponse in an HTTP function.

    using System.IO;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Http;
    using Aliyun.Serverless.Core;
    using Aliyun.Serverless.Core.Http;
    
    using Microsoft.Extensions.Logging;
    namespace MySpace.TestHandlers
    {
        public class SingleHttpHandler : FcHttpEntrypoint
        {
            protected override void Init(IWebHostBuilder builder)
            { 
            }
    
            public override async Task<HttpResponse> HandleRequest(HttpRequest request, HttpResponse response, IFcContext fcContext)
            {
                string method = request.Method;
                string relativePath = request.Path.Value;
                fcContext.Logger.LogInformation("method = {0}; requestPath = {1}", method, relativePath);
    
                StreamReader sr = new StreamReader(request.Body);
                string requestBody = sr.ReadToEnd();
                fcContext.Logger.LogInformation("requestBody = {}", requestBody);
    
                // process request.Headers
    
                response.StatusCode = 200;
                response.Headers["Content-Type"]="text/plain";
                response.Headers.Add("customheader", "v1");
    
                await response.WriteAsync("hello world");
    
                return response;
            }
        }
    }           
    Note If you need to use a single function, see . Create a console project and FcRemoteEntrypoint.cs and change the code to the sample code of a single function.
  • Example of an ASP.NET Core application
    using System;
    using Aliyun.Serverless.Core.Http;
    using Microsoft.AspNetCore.Hosting;
    namespace MySpace.TestWebApi
    {
        public class FcRemoteEntrypoint : FcHttpEntrypoint
        {
             protected override void Init(IWebHostBuilder builder)
            {
                builder
                    .UseStartup<Startup>();
            }
        }
    }          

Procedure

  1. Create a webapi project named asp.net core.
        [songluo@~/tmp]# mkdir fcaspdotnetsample
        [songluo@~/tmp]# cd fcaspdotnetsample
        [songluo@~/tmp/fcaspdotnetsample]# dotnet new webapi                 
  2. Add a package to fcaspdotnetsample.csproj.
    <ItemGroup>
            <PackageReference Include="Aliyun.Serverless.Core" Version="1.0.1" />
            <PackageReference Include="Aliyun.Serverless.Core.Http" Version="1.0.2" />
    </ItemGroup>                  
  3. Create a file named FcRemoteEntrypoint.cs that contains the preceding sample code of the ASP.NET Core application.
  4. Upload the project and compress the target files into a package.
        [songluo@~/tmp/fcaspdotnetsample]# dotnet publish -c Release
        Microsoft (R) Build Engine version 15.9.20+g88f5fadfbe for .NET Core
        Copyright (C) Microsoft Corporation. All rights reserved.
    
      Restore completed in 88.39 ms for /Users/songluo/tmp/fcaspdotnetsample/fcaspdotnetsample.csproj.
      fcaspdotnetsample -> /Users/songluo/tmp/fcaspdotnetsample/bin/Release/netcoreapp2.1/fcaspdotnetsample.dll
      fcaspdotnetsample -> /Users/songluo/tmp/fcaspdotnetsample/bin/Release/netcoreapp2.1/publish/
        [songluo@~/tmp/fcaspdotnetsample]# cd /Users/songluo/tmp/fcaspdotnetsample/bin/Release/netcoreapp2.1/publish/
        [songluo@~/tmp/fcaspdotnetsample/bin/Release/netcoreapp2.1/publish]# zip -r fcaspdotnetsample.zip *
      adding: appsettings.Development.json (deflated 40%)
      adding: appsettings.json (deflated 30%)
      adding: fcaspdotnetsample.deps.json (deflated 85%)
      adding: fcaspdotnetsample.dll (deflated 61%)
      adding: fcaspdotnetsample.pdb (deflated 40%)
      adding: fcaspdotnetsample.runtimeconfig.json (deflated 31%)
      adding: web.config (deflated 40%)
        [songluo@~/tmp/fcaspdotnetsample/bin/Release/netcoreapp2.1/publish]# ls -ll fcaspdotnetsample.zip
        -rw-r--r--  1 songluo  staff  39101 Mar 15 09:47 fcaspdotnetsample.zip                
  5. Use fcaspdotnetsample.zip to create a function with the .NET Core 2.1 runtime and the fcaspdotnetsample::MySpace.TestWebApi.FcRemoteEntrypoint::HandleRequesthandler.

Limits

  • Request limits

    If the function handler request of an HTTP trigger exceeds any of the following limits, the system returns status code 400 and error code InvalidArgument.

    Field Limit HTTP status code Error code
    headers The total size of the keys and values in the request header cannot exceed 4 KB. 400 InvalidArgument
    path The total size of the path and query parameters cannot exceed 4 KB.
    body The body of the HTTP request cannot exceed 6 MB.
  • Response limits

    If the response exceeds any of the following limits, the system returns status code 502 and error code BadResponse.

    Field Limit HTTP status code Error code
    headers The total size of the keys and values in the headers cannot exceed 4 KB. 502 BadResponse
    body The body of the HTTP response cannot exceed 6 MB.

More information

For more information about how to use an HTTP trigger, see Overview.