How can we create an exception filter to handle unhandled exceptions in C#nASP.NET WebAPI?

An exception filter in ASP.NET Web API provides a centralized way to handle unhandled exceptions that occur during controller method execution. When a controller method throws any unhandled exception (except HttpResponseException), the exception filter intercepts it and allows you to customize the HTTP response.

Exception filters implement the System.Web.Http.Filters.IExceptionFilter interface. The simplest approach is to derive from the ExceptionFilterAttribute class and override the OnException method to define custom exception handling logic.

Syntax

Following is the basic syntax for creating a custom exception filter −

public class CustomExceptionFilter : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        if (context.Exception is SpecificExceptionType)
        {
            context.Response = new HttpResponseMessage(HttpStatusCode.StatusCode);
        }
    }
}

Creating a Custom Exception Filter

Below example creates a filter that converts NotFiniteNumberException into HTTP status code 416 (Requested Range Not Satisfiable)

using System;
using System.Net;
using System.Net.Http;
using System.Web.Http.Filters;

namespace DemoWebApplication.Filters
{
    public class CustomExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            if (context.Exception is NotFiniteNumberException)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.RequestedRangeNotSatisfiable)
                {
                    Content = new StringContent(context.Exception.Message),
                    ReasonPhrase = "Invalid Number"
                };
            }
        }
    }
}

Using the Exception Filter in Controller

Here's how to apply the custom exception filter to a Web API controller −

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using DemoWebApplication.Filters;

namespace DemoWebApplication.Controllers
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    [CustomExceptionFilter]
    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;
        }
    }
}

When you call the API with id = 0, the exception filter will catch the NotFiniteNumberException and return a 416 status code with the custom message.

Registration Approaches

Exception filters can be registered at different levels depending on your requirements −

Action Level Registration

[CustomExceptionFilter]
public IHttpActionResult Get(int id)
{
    // Action implementation
    return Ok();
}

Controller Level Registration

[CustomExceptionFilter]
public class StudentController : ApiController
{
    public IHttpActionResult Get(int id)
    {
        return Ok();
    }
}

Global Registration

Register the filter globally in WebApiConfig.cs to handle exceptions across all controllers −

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Filters.Add(new CustomExceptionFilter());
        
        // Other configuration code
        config.MapHttpAttributeRoutes();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Registration Priority

Registration Level Scope Execution Order
Action Level Single action method First
Controller Level All actions in controller Second
Global Level All controllers and actions Last

Conclusion

Exception filters in ASP.NET Web API provide a clean way to handle unhandled exceptions and convert them into appropriate HTTP responses. They can be applied at action, controller, or global levels, offering flexibility in exception handling across your application.

Updated on: 2026-03-17T07:04:36+05:30

532 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements