tags:

views:

87

answers:

2

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.

+1  A: 

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.

Jose Basilio
Yes, I know this. This is where all the stuff for MVC is being registered. There is nothing MVC specific in there though, but I'm guessing there is a way to add some object where I can tap into it. Like when you add a customer model binder, you do this in the global.asax file: "ModelBinders.Binders.Add( typeof( MyModelBinder, new MyModelBinder() );". Then when model binding occurs, your custom class gets called automatically, because you have it registered, which was done in the global.asax file.
Josh Close
+1  A: 

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.

OdeToCode
This is what I was looking for and should work well. I already have a custom controller factory so I can turn sessions off, so adding this is trivial.
Josh Close