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 2 3 4 5 6 7 8 |
public class InterceptionAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { var x = "This is my custom line of code I need executed before any of the controller actions"; base.OnActionExecuting(actionContext); } } |
Then you register this method with GlobalFilters in Global.asax.cs, or with Filters in your WebApiConfig.
1 2 3 4 5 6 7 8 |
public static void ConfigureWebApi(this IAppBuilder app, HttpConfiguration config) { //your other code config.Filters.Add(new InterceptionAttribute()); //your other other code } |
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.
Thanks. Excellent note.
hello,
How do this with net core 3.0/3.1