Asp.net core ASP.NET Core 3中的全局异常处理程序中间件
背景: 我试图找到一种方法,在我的ASP.NET Core 3.0 Webapi中添加一个全局异常处理程序中间件,该中间件可以捕获任何未处理的异常,记录它们并返回ProblemDetails响应 这就是我目前在Startup.cs中得到的信息:(仅包括相关代码)Asp.net core ASP.NET Core 3中的全局异常处理程序中间件,asp.net-core,Asp.net Core,背景: 我试图找到一种方法,在我的ASP.NET Core 3.0 Webapi中添加一个全局异常处理程序中间件,该中间件可以捕获任何未处理的异常,记录它们并返回ProblemDetails响应 这就是我目前在Startup.cs中得到的信息:(仅包括相关代码) public void配置(IApplicationBuilder应用程序,IWebHostEnvironment环境) { app.UseExceptionHandler(新的ExceptionHandlerOptions { Exc
public void配置(IApplicationBuilder应用程序,IWebHostEnvironment环境)
{
app.UseExceptionHandler(新的ExceptionHandlerOptions
{
ExceptionHandler=ProblemDetailsExceptionHandler
});
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(端点=>{endpoints.mapController();});
}
专用异步任务ProblemDetailsCeptionHandler(HttpContext上下文)
{
var requestServiceProvider=context.RequestServices;
var problemDetailsFactory=requestServiceProvider?.GetRequiredService();
if(problemDetailsFactory==null)返回;
if(context.Response.HasStarted)
{
//日志
回来
}
var problemDetails=problemDetailsFactory.CreateProblemDetails(上下文,
StatusCodes.Status500InternalServerError,
详情:“发生错误”);
Add(“内容类型”,新的stringvalue(“应用程序/问题+json”);
wait context.Response.WriteAsync(JsonSerializer.Serialize(problemDetails),Encoding.UTF8);
}
我想要的是:
您可以使用自定义异常过滤器属性,如下所示
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
// if you want to do something special with specific exceptions type
if (context.Exception is TypeOfException)
{
// do something custom
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Result = new JsonResult(
((ValidationException)context.Exception).Failures);
return;
}
var code = HttpStatusCode.InternalServerError;
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.StatusCode = (int)code;
context.Result = new JsonResult(new
{
error = new[] { context.Exception.Message },
stackTrace = context.Exception.StackTrace
});
}
}
然后将其注册到Startup.cs
services.AddControllersWithViews(options => options.Filters.Add(typeof(CustomExceptionFilterAttribute)))
您可以使用自定义异常过滤器属性,如下所示
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
// if you want to do something special with specific exceptions type
if (context.Exception is TypeOfException)
{
// do something custom
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Result = new JsonResult(
((ValidationException)context.Exception).Failures);
return;
}
var code = HttpStatusCode.InternalServerError;
context.HttpContext.Response.ContentType = "application/json";
context.HttpContext.Response.StatusCode = (int)code;
context.Result = new JsonResult(new
{
error = new[] { context.Exception.Message },
stackTrace = context.Exception.StackTrace
});
}
}
然后将其注册到Startup.cs
services.AddControllersWithViews(options => options.Filters.Add(typeof(CustomExceptionFilterAttribute)))
您是否考虑过使用过滤器而不是中间件?在这种情况下,您可以从
ExceptionFilterAttribute
派生,事情可能会简单一点,这并不是问题的真正答案,但您应该看看哪些已经提供了此功能。另外,在ASP.NET核心Web API中还有错误处理功能。谢谢@cremor。我在我的aspnet core 2.2项目中使用了Hellang.Middleware,但我相信3.0应该具有开箱即用的功能?我将看一看ms docsHellang.Middleware.ProblemDetails对于ASP.NET Core 3.0仍然非常有用。仍然缺少一些东西,例如,您是否考虑过使用过滤器而不是中间件?在这种情况下,您可以从ExceptionFilterAttribute
派生,事情可能会简单一点,这并不是问题的真正答案,但您应该看看哪些已经提供了此功能。另外,在ASP.NET核心Web API中还有错误处理功能。谢谢@cremor。我在我的aspnet core 2.2项目中使用了Hellang.Middleware,但我相信3.0应该具有开箱即用的功能?我将看一看ms docsHellang.Middleware.ProblemDetails对于ASP.NET Core 3.0仍然非常有用。仍然缺少一些东西,例如,谢谢,但我不寻求这种方法。我的用例是必须返回ProblemDetails响应的web API。您可以在web API中使用它,error=new[]{context.Exception.Message},
基本上返回问题详细信息。再次感谢,我可以使用context.Features.get()在中间件中获得异常。由于该中间件或该过滤器在出现异常时执行,因此我无法捕获404sThanks,但我不寻找这种方法。我的用例是必须返回ProblemDetails响应的web API。您可以在web API中使用它,error=new[]{context.Exception.Message},
基本上返回问题详细信息。再次感谢,我可以使用context.Features.get()在中间件中获得异常。由于该中间件或该过滤器在出现异常时执行,因此我无法捕获404