22.09.2017 - READING TIME: 2 minutes
Staying Sharp With C# | Part 1
Author: Irhad Babić
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:
If you need to store some data and make it available to methods the most logical place to me is HttpContext. More precisely HttpContext.Current.Items collection which should always be available during a request processing.
So basically, in order to add the item you’ll need later during the request processing, you can do this
And for retrieving it in another place, this
Hope this helps.
Happy coding, have fun.