Base Controller Class and TempData
Need:
To pass information to every view based on an environmental variable. The specific case I ran across this need is when you want to use the minified version of your JavaScript libraries in production and the human readable in dev/QA.
Solution:
- Create your own base controller class.
- Override either onactionexecuting or onactionexecuted.
- Populate TempData with the environment specific information.
- Change your controllers to inherit from your custom base controller
- Use that information in the view.
using System.Configuration;using System.Web.Mvc; namespace BaseController.Controllers{ public class BaseController : Controller { protected override void OnActionExecuting(ActionExecutingContext filterContext) { filterContext.Controller.TempData["OnActionExecuting"] = "OnActionExecuting"; filterContext.Controller.TempData["js_dev"] = ConfigurationManager.AppSettings["js_dev"]; base.OnActionExecuting(filterContext); } protected override void OnActionExecuted(ActionExecutedContext filterContext) { filterContext.Controller.TempData["OnActionExecuted"] = "OnActionExecuted"; filterContext.Controller.TempData["js_prod"] = ConfigurationManager.AppSettings["js_prod"]; base.OnActionExecuted(filterContext); } }}
Pros:
- I’ve found that I often have to create my own base controller class. Doing so for something this simple is a god starting point.
Cons:
Alternate Solutions:
- Use T4 templates to generate a const file based on environment.
- Put the information of each server in the machine.config
Final:
The solution is sound and a sample is attached but I am going to have to come back and flesh out this post a little more with details about the *.config/caching and other options.
No related posts.
No comments yet.