如何创建异常过滤器来处理 C#\ASP.NET WebAPI 中的未处理异常?
csharpserver side programmingprogramming更新于 2025/4/17 20:37:17
当控制器方法抛出任何未处理的异常(不是 HttpResponseException 异常)时,将执行异常过滤器。HttpResponseException 类型是一种特殊情况,因为它是专门为返回 HTTP 响应而设计的。
异常过滤器实现 System.Web.Http.Filters.IExceptionFilter 接口。编写异常过滤器的最简单方法是从 System.Web.Http.Filters.ExceptionFilterAttribute 类派生并重写 OnException 方法。
下面是一个将 NotFiniteNumberException 异常转换为 HTTP 状态代码 416,请求范围不满足 的过滤器。
ExceptionFilterAttribute −
示例
使用 System;
使用 System.Net;
使用 System.Net.Http;
使用 System.Web.Http.Filters;
命名空间 DemoWebApplication.Controllers{
public class ExceptionAttribute : ExceptionFilterAttribute{
public override void OnException(HttpActionExecutedContext context){
if (context.Exception is NotFiniteNumberException){
context.Response = new HttpResponseMessage(HttpStatusCode.RequestedRangeNotSatisfiable);
}
}
}
}
控制器 ActionMethod −
示例
using DemoWebApplication.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace DemoWebApplication.Controllers{
[Exception]
public class StudentController : ApiController{
List<Student> students = new List<Student>{
new Student{
Id = 1,
Name = "Mark"
},
new Student{
Id = 2,
Name = "John"
}
};
public Student Get(int id){
if(id <= 0){
throw new NotFiniteNumberException("The Id is not valid");
}
var studentForId = students.FirstOrDefault(x => x.Id == id);
return studentForId;
}
}
}
因此,让我们通过为控制器操作方法传递 id = 0 来测试上述 ExceptionAttribute。

ExceptionAttribute 可以通过以下任何一种方法注册。
使用异常过滤器装饰操作。
[Exception]
public IHttpActionResult Get(int id){
Return Ok();
}
使用异常过滤器装饰控制器。
[Exception]
public class StudentController : ApiController{
public IHttpActionResult Get(int id){
Return Ok();
}
}
在 WebApiConfig.cs 中全局注册异常。
public static class WebApiConfig{
public static void Register(HttpConfiguration config){
config.Filters.Add(new ExceptionAttribute());
}
}
相关文章
打印
下一节:如何在 C# ASP.NET WebAPI 中使用 accept 标头进行版本控制? ❯❮ 上一节:如何使用 C# ASP.NET WebAPI 中的 Querystring 参数进行版本控制?

