Execute Code on Every Request
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.
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.
In the global.asax
, you can add a handler to Application_BeginRequest
which gets run before every HTTP request. You can also create a custom HTTP module to handle the same.
精彩评论