在函数计算中使用C#编程,需要定义一个函数作为入口函数。为函数设置HTTP触发器后,可以直接处理发来的HTTP请求,方便搭建Web应用。

背景信息

函数计算使用C#编写HTTP函数,需要Nuget引入Aliyun.Serverless.CoreAliyun.Serverless.Core.Http包。

一个简单的C# HTTP函数示例如下所示。

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;
        }
    }
}         

函数入参如下所示:

说明 C# HTTP函数必须继承 Aliyun.Serverless.Core.Http中的 FcHttpEntrypoint,其中 Init函数必须重写, HandleRequest是函数入口 handler,可以根据情况决定是否重写。

函数计算支持两种类型的HTTP函数:

  • 简单的HTTP函数(single function):该类型函数需要重写HandleRequestHandleRequest 实现自定义的逻辑处理。
  • 基于asp.net core Web框架的HTTP函数:该类函数只需要重写Init函数。

HTTP函数限制项

  • 请求限制项

    如果HTTP触发器的函数入口请求超过以下限制,会抛出400状态码和InvalidArgument错误码。

    参数 限制 HTTP状态码 错误码
    headers 请求头中的所有键和值的大小不能超过4 KB。 400 InvalidArgument
    path path以及所有查询参数的大小不能超过4 KB。
    body HTTP请求体的大小不能超过6 MB。
  • 响应限制项

    如果响应超过以下限制,会抛出502状态码和BadResponse错误码。

    参数 限制 HTTP状态码 错误码
    headers headers中的所有键和值的大小不能超过4 KB。 502 BadResponse
    body HTTP响应体的大小不能超过6 MB。

HTTP函数示例

  • Single function示例

    以下示例演示了如何使用HTTP函数中的HttpRequestHttpResponse

    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;
            }
        }
    }           
    说明 如果使用Single function,请参见 C#事件函数,创建console工程,新建 FcRemoteEntrypoint.cs,代码改成Single function示例代码即可。
  • 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>();
            }
        }
    }          

使用步骤

  1. 创建一个名为fcaspdotnetsample的webapi工程。
        [songluo@~/tmp]# mkdir fcaspdotnetsample
        [songluo@~/tmp]# cd fcaspdotnetsample
        [songluo@~/tmp/fcaspdotnetsample]# dotnet new webapi                 
  2. fcaspdotnetsample.csproj中添加包,如下所示。
    <ItemGroup>
            <PackageReference Include="Aliyun.Serverless.Core" Version="1.0.1" />
            <PackageReference Include="Aliyun.Serverless.Core.Http" Version="1.0.2" />
    </ItemGroup>                  
  3. 新建一个名为FcRemoteEntrypoint.cs的文件,文件内容请参见上文Asp.net core application示例代码。
  4. 上传工程并将目标文件打成压缩包。
        [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. 使用fcaspdotnetsample.zip创建runtime为dotnetcore2.1、handlerfcaspdotnetsample::MySpace.TestWebApi.FcRemoteEntrypoint::HandleRequest的函数。

更多信息

HTTP触发器更多使用信息,请参见HTTP触发器概述