Asp – Execute Code on Every Request

asp.net-mvc

I want to be able to execute some code on every request that stuffs data into ViewData. Currently I have a base controller class that all my controllers inherit from and I override OnActionExecuting and do it there.

My only concern with this approach is that whom ever creates a new controller will HAVE to inherit form the base class.

Is there a way to register something in the global.asax, like you would do with custom model binders, that would get ran every request? Kinda like a global action filter or something.

Best Answer

Rather than using a base controller class (which I think is the best option for most scenarios), you could use a custom action invoker. I'd derive from the built-in action invoker and sprinkle in the extra stuff you need. You register the action invoker during app startup in global.asax and it can override OnActionExecuting / OnActionExecuted / OnResultExecuting / OnResultExecuted. You could, for example, use OnResultExecuting to add in some ViewData. At that point you'll know the action completed and also know the type of ActionResult.

Related Topic