代码之家  ›  专栏  ›  技术社区  ›  santosh kumar patro

用于处理WEB API请求的HTTP 4xx错误的ASP.NET COR 2处理程序

  •  0
  • santosh kumar patro  · 技术社区  · 7 年前

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   bobek    7 年前

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

    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();
        }