c# - 用于处理 WEB API 请求的 HTTP 4xx 错误的 ASP.NET COR 2 处理程序
问题描述
与处理 HTTP 5xx 错误的 UseExceptionHandler 类似,ASP.NET CORE 2 是否提供任何处理程序来处理 HTTP 4xx 错误。
在这里,我试图捕获在请求处理管道期间产生的任何 HTTP 4xx 错误,并将其处理并发送回消费者。
解决方案
您可以创建一个新的中间件来处理您的异常:
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();
}
推荐阅读
- if-statement - Haskell中状态的有条件改变
- javascript - 使用 useState Hook 反应 js
- javascript - Chrome 扩展程序
- node.js - 我们的系统中有重复的 Lambda 调用?
- c++ - std::cout 时的 eigen3.3.7 段错误
- linux - 如何设置 systemd 以确保它在服务器关闭/重新启动时停止我的应用程序
- javascript - Javascript:返回的对象未定义
- c - GCC 警告:从 'int' 初始化 'int32_t *' {aka 'int *'} 使指针来自整数而没有强制转换 [-Wint-conversion]
- c - 函数依赖 openMP
- c++ - Sprite::create(“file.png”) 在 Cocos2d-x C++ Visual Studio 上返回 null