How can we run a method before running each Action in MVC3?
I know we can use the following method for OnActionExecuting
:
public cla
You're looking for Controller.ExecuteCore().
This function is called before each action calls. You can override it in a controller or a base controller. Example that sets culture base on cookies from Nadeem Afana:
public class BaseController : Controller
{
protected override void ExecuteCore()
{
string cultureName = null;
// Attempt to read the culture cookie from Request
HttpCookie cultureCookie = Request.Cookies["_culture"];
if (cultureCookie != null)
{
cultureName = cultureCookie.Value;
}
else
{
if (Request.UserLanguages != null)
{
cultureName = Request.UserLanguages[0]; // obtain it from HTTP header AcceptLanguages
}
else
{
cultureName = "en-US"; // Default value
}
}
// Validate culture name
cultureName = CultureHelper.GetImplementedCulture(cultureName); // This is safe
// Modify current thread's cultures
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
base.ExecuteCore();
}
}
I would also suggest looking into AOP, Postsharp or Castle Windsor can easily handle such as task.
Also you could consider use Application_BeginRequest method in global.asax