WebAPI全局捕获控制器异常并返回CustomHttpResponse统一响应
解决方案
你可以通过以下两种方案实现需求,推荐优先选择异常过滤器方案,专门用于处理Controller层抛出的异常:
方案1:使用IExceptionFilter异常过滤器
你之前尝试重写的OnActionExecuting是Action执行前的拦截方法,不负责异常处理,使用专门的异常过滤器即可实现需求:
第一步:实现自定义异常过滤器
public class CustomExceptionFilter : IExceptionFilter { public void OnException(ExceptionContext context) { // 标记异常已被处理,不会继续向上抛出 context.ExceptionHandled = true; // 构造符合要求的统一响应 var result = new CustomHttpResponse { status = 500, message = "Internal Server Error", data = null }; // 设置返回结果 context.Result = new JsonResult(result) { StatusCode = StatusCodes.Status500InternalServerError }; } }
第二步:注册过滤器
在.NET 6+的Program.cs中添加如下配置:
builder.Services.AddControllers(options => { // 注册全局异常过滤器,对所有Controller生效 options.Filters.Add<CustomExceptionFilter>(); });
如果是.NET 5及更早版本,在Startup.cs的ConfigureServices方法中做上述配置即可。
方案2:使用Middleware全局捕获异常
如果你需要捕获整个请求管道的所有异常(不仅是Controller层),可以使用Middleware实现,Invoke方法通过try-catch包裹后续管道逻辑即可:
第一步:实现自定义异常中间件
public class GlobalExceptionHandlingMiddleware { private readonly RequestDelegate _next; public GlobalExceptionHandlingMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { try { // 执行后续中间件/Controller逻辑 await _next(context); } catch (Exception) { // 捕获异常后构造统一响应 context.Response.ContentType = "application/json"; context.Response.StatusCode = StatusCodes.Status500InternalServerError; var response = new CustomHttpResponse { status = 500, message = "Internal Server Error", data = null }; await context.Response.WriteAsJsonAsync(response); } } }
第二步:注册中间件
在Program.cs的最开头添加注册代码,确保可以捕获后续所有环节的异常:
app.UseMiddleware<GlobalExceptionHandlingMiddleware>(); // 后续再添加其他中间件,如UseRouting、UseAuthorization等
内容的提问来源于stack exchange,提问作者Nexicolt
相关产品推荐
相关产品推荐

