用例:我想使用自定义中间件对 http 触发字符串响应进行最后一刻的修改。
我将自定义中间件编写为:
internal sealed class MyCustomMiddleware : IFunctionsWorkerMiddleware
{
public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
{
await next(context); //returns "Hello"
//I want modify response to becomes "Hello World"
}
}
我将自定义中间件注册为:
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults(worker =>
{
worker.UseMiddleware<MyCustomMiddleware>();
})
.Build();
host.Run();
函数执行后无法提取响应字符串“Hello”。我尝试使用 GetHttpResponseData() 但它返回 null。
context.GetHttpResponseData().Body
我尝试了下面的代码来提取Http触发的Azure函数的响应并在自定义中间件中修改其上下文。
自定义中间件:
public sealed class MyCustomMiddleware : IFunctionsWorkerMiddleware
{
public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
{
// Fetching the Http Azure function response
var req = await context.GetHttpRequestDataAsync();
// Modifying the response
var res = req!.CreateResponse();
await res.WriteStringAsync("Function response changed");
context.GetInvocationResult().Value = res;
}
}
程序.cs:
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults(worker =>
{
worker.UseMiddleware<MyCustomMiddleware>();
})
.ConfigureServices(services =>
{
services.AddApplicationInsightsTelemetryWorkerService();
services.ConfigureFunctionsApplicationInsights();
})
.Build();
host.Run();
控制台输出:
Azure Functions Core Tools
Core Tools Version: 4.0.5455 Commit hash: N/A (64-bit)
Function Runtime Version: 4.27.5.21554
[2023-12-13T12:15:21.065Z] Found C:\Users\<user>\Source\Repos\FunctionApp18\FunctionApp18\FunctionApp18.csproj. Using for user secrets file configuration.
[2023-12-13T12:15:31.028Z] Azure Functions .NET Worker (PID: 26252) initialized in debug mode. Waiting for debugger to attach...
[2023-12-13T12:15:31.229Z] Worker process started and initialized.
Functions:
Function1: [GET,POST] http://localhost:7299/api/Function1
For detailed output, run func with --verbose flag.
[2023-12-13T12:15:36.296Z] Host lock lease acquired by instance ID '000000000000000000000000XXXXXXC'.
[2023-12-13T12:15:44.167Z] Executing 'Functions.Function1' (Reason='This function was programmatically called via the host APIs.', Id=7f684090-4XXXXXXXXXXXXe-1f825fe62a1f)
[2023-12-13T12:15:44.489Z] Executed 'Functions.Function1' (Succeeded, Id=7f684090-46a6-XXXXXXXXXXXXXX-1f825fe62a1f, Duration=363ms)
初步回应:
修改后的回复: