Asp.net core - invoke method() 不在中间件中调用

Sia*_*ash 5 c# logging middleware .net-core asp.net-core

我熟悉中间件概念,并且在我的项目中实现了许多中间件。我还阅读了Microsoft 文档中的ASP.NET Core 中间件文档。但这一次我遇到了令人困惑的问题,实际上我编写了一个简单的中间件来为每个请求写入日志。

这是我的中间件类:

public class LoggerMiddleware
{
    private readonly RequestDelegate _next;

    public LoggerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext httpContext, LogDbContext dbContext)
    {
        var logInfo = await Logger.InitiateLogging(httpContext, dbContext);
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            await Logger.AddException(httpContext, ex, true);
        }
        finally
        {
            await Logger.PersistLog(logInfo, httpContext);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我声明了一个扩展方法:

public static class LoggingMiddlewareExtensions
{
    public static IApplicationBuilder UseLogger(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<LoggerMiddleware>();
    }
}
Run Code Online (Sandbox Code Playgroud)

最后我在 Startup.cs 上调用了UseLogger方法Configure。

这是我的startup.cs代码:

public void Configure(
    IApplicationBuilder app,
    IHostingEnvironment env,
    ILoggerFactory loggerFactory,
    IServiceScopeFactory scopeFactory,
    IOptions<BaranSettings> baranSettings)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();


    // other lines of code...
    app.UseLogger();
    // other lines of code...
}
Run Code Online (Sandbox Code Playgroud)

问题:

问题是LoggerMiddleware调用了构造函数,但Invoke没有调用该方法。有谁知道问题是什么?