Code execution for each request

I want to be able to execute some code for every request that stores data in ViewData. I currently have a base controller class that inherits all my controllers, and I override OnActionExecuting and do it there.

My only concern with this approach is that whoever ever creates a new controller HOPES to inherit the form of the base class.

Is there a way to register something in global.asax, as with custom model bindings that will trigger each request? Kinda as a global action filter or something like that.

+4
source share
2 answers

Instead of using the base class of the controller (which, in my opinion, is the best option for most scenarios), you can use a custom action invoker , I would get from the built-in action invoker and sprinkle extra things that you need. You register an invoker action during application startup in global.asax and you can override OnActionExecuting / OnActionExecuted / OnResultExecuting / OnResultExecuted. For example, you can use OnResultExecuting to add to some ViewData. At this point, you will find out that the action is complete, and also recognize the type of ActionResult.

+2
source

In global.asax you can add a handler to the Application_BeginRequest , which runs before each HTTP request. You can also create a custom HTTP module to handle the same.

+2
source

All Articles