我熟悉中间件的概念,并且在我的项目中实现了许多中间件。此外,我还阅读了微软文档中的ASP.NET核心中间件文档。但这一次我遇到了一个令人困惑的问题,实际上我写了一个简单的中间来写每个请求的日志。
这是我的中间件类:
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并注入ILoggerFactory:
为什么ASP.NET Core DI知道如何解决ILogger<T>,但不是ILogger?
另请参阅:
如何使用LoggerFactory和Microsoft.Extensions.Logging for.NET Core Logging With C#