【发布时间】: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