[英]Asp.net core - The invoke method() doesn't call in Middleware
I familiar with Middleware concept and I had implemented many Middlewares on my project. 我熟悉中间件概念,并且在我的项目中实现了许多中间件。 And also I read ASP.NET Core Middleware documentation at Microsoft docs.
我还阅读了Microsoft docs的ASP.NET核心中间件文档。 But this time I faced with confusing problem, Actually I wrote a simple middle to write logs per each requests.
但是这次我遇到了令人困惑的问题,实际上我写了一个简单的中间来为每个请求写日志。
This is my middleware class: 这是我的中间件类:
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);
}
}
}
Then I declared an extension-method: 然后我宣布了一个扩展方法:
public static class LoggingMiddlewareExtensions
{
public static IApplicationBuilder UseLogger(this IApplicationBuilder builder)
{
return builder.UseMiddleware<LoggerMiddleware>();
}
}
And finally I called UseLogger
method on Configure
on Startup.cs. 最后我在Startup.cs上的
Configure
上调用了UseLogger
方法。
This is my startup.cs code: 这是我的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...
}
Problem : 问题 :
The problem is LoggerMiddleware
constructor called, but the Invoke
method doesn't call. 问题是
LoggerMiddleware
构造函数被调用,但是Invoke
方法没有调用。 Does any one know what is the problem? 有谁知道这是什么问题?
For this particular use case, I would strongly urge you to consider using .Net Core DI and inject an ILoggerFactory: 对于这个特殊用例,我强烈建议您考虑使用.Net Core DI并注入ILoggerFactory:
Why ASP.NET Core DI knows how to resolve ILogger<T>, but not ILogger? 为什么ASP.NET Core DI知道如何解决ILogger <T>,而不是ILogger?
See also: 也可以看看:
How to Use LoggerFactory and Microsoft.Extensions.Logging for .NET Core Logging With C# 如何使用LoggerFactory和Microsoft.Extensions.Logging进行.NET核心日志记录与C#
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.