我熟悉中间件的概念,并且在我的项目中实现了许多中间件。另外,我还阅读了Microsoft文档中的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的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...
}
问题:
问题是调用了LoggerMiddleware
构造函数,但是没有调用Invoke
方法。
有人知道是什么问题吗?
答案 0 :(得分:4)
对于此特定用例,我强烈建议您考虑使用.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#