![](/img/trans.png)
[英]ASP.NET Core ViewComponent's Invoke() method call not recognized
[英]Asp.net core - The invoke method() doesn't call in Middleware
我熟悉中間件概念,並且在我的項目中實現了許多中間件。 我還閱讀了Microsoft docs的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進行.NET核心日志記錄與C#
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.