【问题标题】:Handle all errors from global handling exception in Web API Core 3.1在 Web API Core 3.1 中处理来自全局处理异常的所有错误
【发布时间】: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


    【解决方案1】:

    这是一个工作演示:

    1.ExceptionMiddleware:

    public static class ExceptionMiddleware
    {
        public static void ConfigurationExceptionHandler(this IApplicationBuilder app)
        {
            app.UseStatusCodePagesWithReExecute("/Error/{0}");
            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)
                            {
                                var data = new ApiResponse(context.Response.StatusCode, null);
                                var response = JsonSerializer.Serialize(data);
                                await context.Response.WriteAsync(response);
                            }
                            
                        });
                }
          );          
        }
    }
    

    2.ErrorController:

    [ApiController]
    [Route("[controller]")]
    public class ErrorController : ControllerBase
    {
        [Route("{code}")]
        public IActionResult InternalError(int code)
        {
            return new ObjectResult(new ApiResponse(code));
        }
    }
    

    3.ApiResponse:

    public class ApiResponse
    {
        public int StatusCode { get; set; }
        public string Description { get; set; }
        public ApiResponse(int statusCode, string description = null)
        {
            StatusCode = statusCode;
            Description = description ?? GetDefaultMessageForStatusCode(statusCode);
        }
    
        private static string GetDefaultMessageForStatusCode(int statusCode)
        {
            switch (statusCode)
            {
    
                case 404:
                    return "Resource not found";
                case 500:
                    return "Internal server message";
                case 401:
                    return "UnAuthorized!";
                default:
                    return null;
            }
        }
    }
    

    4.测试:

    // [ApiController]   //be sure remove this for asp.net core 3.1
    [Route("[controller]")]
    public class TestController : ControllerBase
    {
        
        [HttpGet]
        public IActionResult Get()
        {
            //throw new Exception("sad");  //500
            //return Unauthorized();   //401
            return NotFound();         //404
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-05
      • 2017-10-12
      • 1970-01-01
      • 2011-04-07
      • 2016-12-02
      • 1970-01-01
      • 1970-01-01
      • 2021-01-21
      相关资源
      最近更新 更多