views:

392

answers:

2

I've got some things I do in the OnActionExecuting method in a BaseController, that all my other controllers are based off of.

I'm doing some simple things like putting a variable into ViewData that "nearly" all of my views will need, and populating a couple properties that my controllers use.

Thing that bugs me is, this work is being done even on actions that don't need it. Is there a better place to hook into to more efficiently perform this work? In case I ever need to something a little "heavier" than what I do now (i.e. DB access, etc...).

UPDATE: I'm more specifically referring to a typical controller scenario. Where there are several actions that simply show a view. And a few that take a form submission, do some work, and redirect to another action.

In this case, I want the actions that show views to use the work that is done in the OnActionExecuting method. But the actions that accept form submissions, the work being done in OnActionExecuting is not being used and therefor just adds unnecessary processing time.

Maybe I'm not explaining it very well... hope it's clearer now.

TIA!

A: 

Create a second "AdvancedBaseController" which derives from BaseController?

pb
Well, in my typical controller... there are actions that simply show views. Those I do want using the work that I'm performing in the BaseController. There are some actions, such as the actions that receive a post to do some work on the backend before redirecting to another action. I'd like to exclude only those from taking part in OnActionExecuting, as it would simply be adding processing time to those requests - which don't need the data.
Chad
+2  A: 

If it's easier to blacklist actions (by attributing actions for which this logic shouldn't be performed) than whitelisting actions, you could create a [SuppressWhateverLogic] attribute and apply it to the methods you want to be blacklisted. Then modify your OnActionExecuting() method to look for this attribute (via ActionExecutingContext.ActionDescriptor.IsDefined()), and if the attribute exists then bail out of the logic.

If it's easier to whitelist actions, move the logic out of Controller.OnActionExecuting() and create a custom [MyLogic] filter by subclassing ActionFilterAttribute. Add the logic to MyLogicAttribute.OnActionExecuting(), then attribute the methods you want with [MyLogic] to associate the logic with those methods.

Levi
I'm not currently at a place where I can access my code, but that sounds like a reasonable solution. Thank you!
Chad