【发布时间】:2020-11-08 07:51:59
【问题描述】:
我在 Web API Core 3.1 中实现了全局异常处理,因此我只能处理 500 错误,但我需要处理所有错误,如 500、401、404、402。我该如何实现?
public static class ExceptionMiddleware
{
public static void ConfigurationExceptionHandler(this IApplicationBuilder app)
{
app.UseExceptionHandler(
appErr =>
{
appErr.Run(
async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.ContentType = "application/json";
var contexFeature = context.Features.Get<IExceptionHandlerFeature>();
if (contexFeature != null)
{
await context.Response.WriteAsync(new ApiResponse{
StatusCode=context.Response.StatusCode,
Description="Internal server message"
}.ToString());
}
});
}
);
}
}
在启动文件中:
app.ConfigurationExceptionHandler();
【问题讨论】:
标签: c# asp.net-core-mvc asp.net-core-webapi