Understanding .NET Framework Web API Global Exception Filter Implementation

Updated on: March 26, 2021

Implement the below steps for adding Global and Custom Exception Filter to use throughout the .NET Framework's Web API application:

Step 1: Create .NET Framework's Web API application (We are using .NET Framework 4.7.2):

Open Visual Studio => File Menu => New => Project => Select ASP.NET Web Application (.NET Framework), click on "Next" button, provide Project Name, Location of the Project, Solution Name and Framework of the application and click on "Create" button and on the next screen  to create the application as shown below:

Step 2: Add EmployeeController.cs Web API Controller and add the below code:

  1. using System.Web.Http;
  2. namespace EmployeeManagementAPI.Controllers
  3. {
  4.     public class EmployeeController : ApiController
  5.     {
  6.         public IHttpActionResult Get()
  7.         {
  8.             int a = 50, b = 0, c = a / b;
  9.             return Ok("Employees:[{Id:1,Name:'John'},{Id:2,Name:'Brian'}]");
  10.         }
  11.     }
  12. }

If you see in the above code at line number 5, there is a "Divide by Zero" exception, so when user is calling this API method, it should come out of the loop from line number 5 and give exception error output as shown below:

Step 3: Now, we are going to add Global Exception Filter Class

Create Filters folder in the application and add EmployeeExceptionFilter.cs class with below code:

  1. using System.Net;
  2. using System.Net.Http;
  3. using System.Web.Http.Filters;
  4. namespace EmployeeManagementAPI.Filters
  5. {
  6.     public class EmployeeExceptionFilter : ExceptionFilterAttribute
  7.     {
  8.         public override void OnException(HttpActionExecutedContext actionExecutedContext)
  9.         {
  10.             var responseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError)
  11.             {
  12.                 Content = new StringContent("An unhandled exception was thrown by Employee Service."),
  13.                 ReasonPhrase = "Internal Server Error Occurred. Please Contact your Administrator."
  14.             };
  15.             actionExecutedContext.Response = responseMessage;
  16.         }
  17.     }
  18. }

The above EmployeeExceptionFilter class is Custom Exception filter which is inherited from ExceptionFilterAttribute. This class can be used as Global Exception filter for entire application or can be used specifically at Controller level or at Action level.

Step 4: Now, Register the EmployeeExceptionFilter as Global Exception filter in Register() method of WebApiConfig.cs class in App_Start folder

  1. using EmployeeManagementAPI.Filters;
  2. using System.Net.Http.Formatting;
  3. using System.Web.Http;
  4. namespace EmployeeManagementAPI
  5. {
  6.     public static class WebApiConfig
  7.     {

  8.         public static void Register(HttpConfiguration config)
  9.         {
  10.             // Web API configuration and services
  11.             config.Formatters.Clear();
  12.             config.Formatters.Add(new JsonMediaTypeFormatter());
  13.             config.Filters.Add(new EmployeeExceptionFilter()); 
  14.             // Web API routes
  15.             config.MapHttpAttributeRoutes();

  16.             config.Routes.MapHttpRoute(
  17.                 name: "DefaultApi",
  18.                 routeTemplate: "api/{controller}/{id}",
  19.                 defaults: new { id = RouteParameter.Optional }
  20.             );
  21.         }
  22.     }
  23. }

After adding EmployeeExceptionFilter class in the above Register method, it will be applicable for entire application and it will start handing Exception for entire application. 

Once you run the Web API and access the EmployeeController=>Get() method, it will show the below Exception result:

You can try implementing above Global Exception filter in your .NET Framework's Web API application, if you want to implement it at Controller level and not to implement at Global level, then comment out "config.Filters.Add(new EmployeeExceptionFilter());" line in above Register() method of WebApiConfig.cs class and add attribute as [EmployeeExceptionFilter] at the above of Controller class declaration.