Bộ lọc ngoại lệ (Exception Filter) được thực thi khi phương thức controller ném ra bất kỳ ngoại lệ chưa được xử lý nào không phải là ngoại lệ HttpResponseException. Loại HttpResponseException là trường hợp đặc biệt, vì nó được thiết kế đặc biệt để trả về phản hồi HTTP.
Exception filters triển khai interface System.Web.Http.Filters.IExceptionFilter. Cách đơn giản nhất để viết exception filter là kế thừa từ lớp System.Web.Http.Filters.ExceptionFilterAttribute và ghi đè phương thức OnException.
Dưới đây là một filter chuyển đổi ngoại lệ NotFiniteNumberException thành mã trạng thái HTTP 416 - Requested Range Not Satisfiable.
ExceptionFilterAttribute
using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;
namespace DemoWebApplication.Controllers
{
public class ExceptionAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
if (context.Exception is NotFiniteNumberException)
{
context.Response = new HttpResponseMessage(HttpStatusCode.RequestedRangeNotSatisfiable);
}
}
}
}
Controller Action Method
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 students = new List
{
new Student { Id = 1, Name = "Mark" },
new Student { Id = 2, Name = "John" }
};
public Student Get(int id)
{
if (id <= 0)
{
throw new NotFiniteNumberException("Id không hợp lệ");
}
var studentForId = students.FirstOrDefault(x => x.Id == id);
return studentForId;
}
}
}
Hãy test ExceptionAttribute bằng cách truyền id = 0 cho phương thức hành động controller.

ExceptionAttribute có thể được đăng ký theo các cách sau:
1. Trang trí Action với exception filter
[Exception]
public IHttpActionResult Get(int id)
{
return Ok();
}
2. Trang trí Controller với exception filter
[Exception]
public class StudentController : ApiController
{
public IHttpActionResult Get(int id)
{
return Ok();
}
}
3. Đăng ký exception toàn cục trong WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new ExceptionAttribute());
}
}