Understanding .NET Framework Web API Global Exception Filter Implementation
There are different ways to handle Exception in .NET Framework's Web API, in this article we will be understanding how to add Global Exception filter in .NET Framework's Web API application. Global exception filter applies to all the Controller and all the API methods inside the controller, we don't have to specify as Attribute above any controller or action method. Below steps shows how to add or implement Global and Custom Exception Filter in our .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:
- using System.Web.Http;
- namespace EmployeeManagementAPI.Controllers
- {
- public class EmployeeController : ApiController
- {
- public IHttpActionResult Get()
- {
- int a = 50, b = 0, c = a / b;
- return Ok("Employees:[{Id:1,Name:'John'},{Id:2,Name:'Brian'}]");
- }
- }
- }
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:
- using System.Net;
- using System.Net.Http;
- using System.Web.Http.Filters;
- namespace EmployeeManagementAPI.Filters
- {
- public class EmployeeExceptionFilter : ExceptionFilterAttribute
- {
- public override void OnException(HttpActionExecutedContext actionExecutedContext)
- {
- var responseMessage = new HttpResponseMessage(HttpStatusCode.InternalServerError)
- {
- Content = new StringContent("An unhandled exception was thrown by Employee Service."),
- ReasonPhrase = "Internal Server Error Occurred. Please Contact your Administrator."
- };
- actionExecutedContext.Response = responseMessage;
- }
- }
- }
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
- using EmployeeManagementAPI.Filters;
- using System.Net.Http.Formatting;
- using System.Web.Http;
- namespace EmployeeManagementAPI
- {
- public static class WebApiConfig
{
- public static void Register(HttpConfiguration config)
- {
- // Web API configuration and services
- config.Formatters.Clear();
- config.Formatters.Add(new JsonMediaTypeFormatter());
- config.Filters.Add(new EmployeeExceptionFilter());
- // Web API routes
- config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
- }
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.