首页 > 解决方案 > 用于处理 WEB API 请求的 HTTP 4xx 错误的 ASP.NET COR 2 处理程序

问题描述

与处理 HTTP 5xx 错误的 UseExceptionHandler 类似,ASP.NET CORE 2 是否提供任何处理程序来处理 HTTP 4xx 错误。

在这里,我试图捕获在请求处理管道期间产生的任何 HTTP 4xx 错误,并将其处理并发送回消费者。

标签: c#asp.net-core-2.1

解决方案


您可以创建一个新的中间件来处理您的异常:

public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;

    /// <summary>
    /// Default constructor
    /// </summary>
    /// <param name="next">Next request in the pipeline</param>
    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    /// <summary>
    /// Entry point into middleware logic
    /// </summary>
    /// <param name="context">Current http context</param>
    /// <returns></returns>
    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (HttpException httpException)
        {
            context.Response.StatusCode = httpException.StatusCode;
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var code = HttpStatusCode.InternalServerError; // 500 if unexpected

        var result = JsonConvert.SerializeObject(new { Error = "Internal Server error" });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;
        return context.Response.WriteAsync(result);
    }
}

像这样在你的Startup.cs

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseMiddleware(typeof(ErrorHandlingMiddleware));

        app.UseMvc();
    }

推荐阅读