我的 Azure 函数上的 IFunctionsWorkerMiddleware 未调用

问题描述 投票:0回答:1

我正在尝试为我的azure函数类型httprequest实现一个中间件,我在.net 6上使用接口IFunctionsWorkerMiddleware

public class HistoryLogMiddleware : IFunctionsWorkerMiddleware
{
  public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
  {
    var requestData = await context.GetHttpRequestDataAsync();
    var body = await new StreamReader(requestData.Body).ReadToEndAsync();

    Console.WriteLine($"Request Body: {body}");

    await next(context);

    var responseData =  context.GetHttpResponseData().Body;
    var resp = await new StreamReader(responseData).ReadToEndAsync();

    Console.WriteLine($"Response: {resp}");
  }
}

在我的startup课上:

[assembly: FunctionsStartup(typeof(Startup))]

public class Startup : FunctionsStartup
{
  public override void Configure(IFunctionsHostBuilder builder)
  {
    builder.Services.AddDatabases();
    builder.Services.AddExternals();
    builder.Services.AddUseCases();

    builder.Services.AddSingleton<HistoryLogMiddleware>();
  }
}

测试功能,域类工作正常(因为控制台显示...),但中间件从未在控制台上注册或在调试模式下附加。

我的功能

public class RegisterClientFunction
{
  private readonly IClientsDomain _clientsDomain;
  public RegisterClientFunction(IClientsDomain clientsDomain)
  {
    _clientsDomain = clientsDomain;
  }

  [FunctionName(nameof(RegisterClientFunction))]
  public async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
    ILogger log)
  {
    log.LogInformation("C# HTTP trigger function processed a request.");

    string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
    var data = JsonConvert.DeserializeObject<RegisterClientRequest>(requestBody);

    var resp = await ExecuterDomain.ExecuteAsync(() => _clientsDomain.RegisterClient(data));
    return new ObjectResult(resp);
  }
}

有人知道为什么中间件没有被调用吗?

miiddleware not invoke console

c# .net azure-functions httprequest middleware
1个回答
0
投票

您似乎尚未将中间件添加到函数执行管道中。以下是如何使用它。

public class RegisterClientFunction
{
    private readonly IClientsDomain _clientsDomain;
    private readonly HistoryLogMiddleware _historyLogMiddleware;

    public RegisterClientFunction(IClientsDomain clientsDomain, HistoryLogMiddleware historyLogMiddleware)
    {
        _clientsDomain = clientsDomain;
        _historyLogMiddleware = historyLogMiddleware;
    }

    [FunctionName(nameof(RegisterClientFunction))]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        // Use your middleware
        var context = new FunctionContext(req, log);
        await _historyLogMiddleware.Invoke(context, null);

        //your code
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.