How to intercept all incoming requests with WebAPI

As a part of a bigger task, I had to intercept all of the incoming client requests to our WebAPI controllers.

I considered several options, like fiddling with HttpModule, or using the Application_BeginRequest method in Global.asax.cs, but settled for whole another one.

Basically what I suggest you do is create a public class which inherits from ActionFilterAttribute. Then you override OnActionExecuting(HttpActionContext actionContext) method, and add your code to it.

Then you register this method with GlobalFilters in Global.asax.cs, or with Filters in your WebApiConfig.

If you’re running your project on .NET Core you won’t be able to register your filter in Global.asax.cs or WebApiConfig. What you can do is you can register a filter globally (for all controllers and actions) by adding it to the MvcOptions.Filters collection in the ConfigureServices method in the Startup class.

This is why I prefer this approach to others:

  • It allows for a very easy expansion. For example, I can easily add override method for OnActionExecuted, if I need to deal with something at the END OF EVERY REQUEST, or I can override methods for async methods, etc.
  • It works ONLY for requests, more specifically the ones that have an actual route
  • It’s clean and easy to understand and maintain

Happy coding, and have fun.

2 thoughts on “How to intercept all incoming requests with WebAPI

Leave a Reply

Your email address will not be published. Required fields are marked *