【问题标题】:Asp.net core - The invoke method() doesn't call in MiddlewareAsp.net core - 调用方法()不在中间件中调用
【发布时间】:2019-04-07 07:22:06
【问题描述】:

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

这是我的中间件类:

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);
        }
    }
}

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

public static class LoggingMiddlewareExtensions
{
    public static IApplicationBuilder UseLogger(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<LoggerMiddleware>();
    }
}

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

这是我的 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...
}

问题:

问题是调用了LoggerMiddleware 构造函数,但没有调用Invoke 方法。 有谁知道问题出在哪里?

【问题讨论】:

    标签: c# logging asp.net-core .net-core middleware


    【解决方案1】:

    对于这个特殊用例,我强烈建议您考虑使用 .Net Core DI 并注入 ILoggerFactory:

    Why ASP.NET Core DI knows how to resolve ILogger<T>, but not ILogger?

    另见:

    How to Use LoggerFactory and Microsoft.Extensions.Logging for .NET Core Logging With C#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-11
      • 2021-02-06
      • 2021-01-18
      • 1970-01-01
      • 2019-06-17
      • 2020-02-20
      • 2018-02-28
      相关资源
      最近更新 更多