請求處理程序(Handler)
更新時間 2024-12-10 11:37:49
最近更新時間: 2024-12-10 11:37:49
分享文章
本文介紹如何使用C#請求處理程序響應接收到的事件并執行相應的業務邏輯。
請求處理程序
請求處理程序是一個執行的入口方法,當您的函數被調用時,函數計算會運行該方法處理請求。
您可以通過函數計算控制臺頁面配置請求處理程序,對于C#語言的函數,請求處理程序需配置為 [程序集名稱]::[命名空間].[類名]::[方法名]。例如,您的程序集名稱為HelloApp,命名空間為Example,方法名為Hello,方法名為Handler,則請求處理程序可配置為 HelloApp::Example.Hello::Handler。
如下是一個請求處理程序的方法實現示例:
using System;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Serverless.Cf;
namespace Example
{
public class Hello
{
public async Task<Stream> Handler(Stream input, ICfContext context)
{
}
static void Main(string[] args) { }
}
}
請求處理程序支持以下方法簽名:
// 包含ICfContext的同步方法
OutType Handler(InType input, ICfContext context);
// 不包含ICfContext的同步方法
OutType Handler(InType input);
// 包含ICfContext的異步方法
Async Task<OutType> Handler(InType input, ICfContext context);
// 不包含ICfContext的異步方法
Async Task<OutType> Handler(InType input);
方法簽名說明:
- 方法名稱:方法名稱可自定義。
- 返回值:
void、System.IO.Stream或可以被JSON序列化和反序列化的對象。 - 方法入參:第一個入參是
System.IO.Stream或可以被JSON序列化和反序列化的對象;第二個入參可選,當存在第二個入參時,必須是ICfContext類型。
如果您使用到ICfContext接口,需要在代碼目錄下的csproj文件引入Serverless.Cf依賴:
<ItemGroup>
<PackageReference Include="Serverless.Cf" Version="1.0.0" />
</ItemGroup>
示例:Event Handler
public async Task<Stream> Handler(Stream input, ICfContext context)
{
var str = "Hello world";
byte[] bytetxt = Encoding.UTF8.GetBytes(str);
context.Logger.LogInformation("Hello: " + str);
MemoryStream output = new MemoryStream();
await input.CopyToAsync(output);
output.Write(bytetxt, 0, bytetxt.Length);
return output;
}
示例:Http Handler
public HTTPTriggerResponse Handler(HTTPTriggerEvent input, ICfContext context)
{
var str = JsonSerializer.Serialize(input);
context.Logger.LogInformation("Hello log: " + str);
return new HTTPTriggerResponse
{
StatusCode = 200,
IsBase64Encoded = false,
Body = str
};
}