Mistral logo

Staying Sharp With C# | Part 1

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.

1

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

 2

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

How to store data per request with WebAPI

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

11

And for retrieving it in another place, this

22

Hope this helps.

Happy coding, have fun.