在函数计算中使用C#编程,需要定义一个函数作为入口函数。为函数设置HTTP触发器后,可以直接处理发来的HTTP请求,方便搭建Web应用。
背景信息
函数计算使用C#编写HTTP函数,需要Nuget引入Aliyun.Serverless.Core
和Aliyun.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;
}
}
}
函数入参如下所示:
-
IFcContext参数与事件函数的IFcContext接口相同。
Aliyun.Serverless.Core.Http
中的
FcHttpEntrypoint
,其中
Init
函数必须重写,
HandleRequest
是函数入口
handler
,可以根据情况决定是否重写。
函数计算支持两种类型的HTTP函数:
- 简单的HTTP函数(single function):该类型函数需要重写
HandleRequest
,HandleRequest
实现自定义的逻辑处理。 - 基于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函数中的
HttpRequest
和HttpResponse
。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>(); } } }
使用步骤
更多信息
HTTP触发器更多使用信息,请参见HTTP触发器概述。