我熟悉中间件的概念,并且在我的项目中实现了很多中间件。我还读了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/