c# - Asp.net 核心 - 调用方法()不调用中间件

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

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

这是我的中间件类:

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 方法。 有谁知道是什么问题吗?

最佳答案

对于这个特定的用例,我强烈建议您考虑使用 .Net Core DI 并注入(inject)一个 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#

关于c# - Asp.net 核心 - 调用方法()不调用中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53128886/

相关文章:

c# - 哪段代码性能更高?

c# - 如何将 MediatR PublishStrategy 添加到现有项目

PHP - 记录用户事件并将其显示在不同页面上的最佳方式?

c# - 选择 webApi 模板时如何将 ASP.Net 身份添加到 Asp.Net Core?

c# - UDP端口开放检查

c# - 如何在c#项目中集成python库

python - 使用 dictConfig 的 Django 日志记录找不到 "logging"模块

php - Symfony 3开发人员页面无法正确显示

mysql - 如何使用 MysqlStorage 在版本 1.6 中增加 Hangfire 超时

asp.net-core - ActionResult<bool> 中的隐式转换运算符不起作用