类似于处理HTTP 5xx错误的UseExceptionHandler,ASP.NET CORE 2是否提供任何处理程序来处理HTTP 4xx错误。
在这里,我试图捕获在请求处理管道中产生的所有HTTP 4xx错误,并将其发送回使用者。
答案 0 :(得分:0)
您可以创建一个新的中间件来处理您的异常:
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();
}