我想创建一个AspNetCore中间件(旧的IHttpModule),它应该捕获异常(稍后保存它们或类似的东西)
但是,我不知道如何捕获Middleware中的Exception,尽管HttpStatusCode是500
这是我有的:
// Middleware
internal class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next.Invoke(context);
}
catch (Exception ex)
{
// never gets here
}
// 500
HttpStatusCode statusCode = (HttpStatusCode)context.Response.StatusCode;
// how to get error message?
}
}
// Middleware Extension method
public static class ExceptionMiddlewareExtensions
{
public static IApplicationBuilder UseExceptionMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<ExceptionMiddleware>();
}
}
// Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseExceptionMiddleware();
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
我触发了这样的异常:
public IActionResult Index()
{
var test = 0;
var a = 100 / test;
return View();
}
您正确地在中间件中使用try-catch
。
但你的问题是你也注册了ExceptionHandler middleware(app.UseExceptionHandler
)。此中间件捕获所有未处理的异常,并设置500状态代码,如果可以处理它。
作为一种可能的解决方案,考虑交换中间件的顺序,因此您的中间件将是第一个捕获管道中进一步发生的异常的中间件:
app.UseExceptionHandler("/Home/Error");
app.UseExceptionMiddleware();
你正在重新发明轮子。
如何在没有自己的中间件的情况下正确完成:
您可以使用内置的ExceptionHandlerMiddleware
(app.UseExceptionHandler
)获取错误详细信息ASP.NET Core为您提供,但未记录,但它应该是。
因此,您可以通过HttpContext.Features
访问您的异常详细信息:
假设您在/Home/Error
控制器的操作中调用它,您可以像下面这样访问它:
var exHandlerFeature = HttpContext.Features.Get<IExceptionHandlerFeature>();
var exception = exHandlerFeature.Error;