在函数计算中使用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接口相同。
说明 C# HTTP函数必须继承
Aliyun.Serverless.Core.Http
中的FcHttpEntrypoint
,其中Init
函数必须重写,HandleRequest
是函数入口handler
,可以根据情况决定是否重写。
函数计算支持两种类型的HTTP函数:
- 简单的HTTP函数(single function):该类型函数需要重写
HandleRequest
,HandleRequest
实现自定义的逻辑处理。 - 基于asp.net core Web框架的HTTP函数:该类函数只需要重写
Init
函数。
限制说明
- 请求限制
如果超过以下限制,会返回
400
状态码和InvalidArgument
错误码。字段 限制说明 HTTP状态码 错误码 headers 请求头中的所有键和值的总大小不能超过4 KB。 400 InvalidArgument path 请求路径以及所有查询参数的总大小不能超过4 KB。 body 同步调用请求的Body的总大小不能超过16 MB,异步调用请求的Body的总大小不能超过128 KB。 - 响应限制
如果超过以下限制,会返回
502
状态码和BadResponse
错误码。字段 限制说明 HTTP状态码 错误码 headers 响应头中的所有键和值对的大小不能超过4 KB。 502 BadResponse body 同步调用响应的Body的总大小不能超过16 MB,异步调用响应的Body的总大小不能超过128 KB。
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,请参见事件函数完整示例,创建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触发器概述。