Run a method before each Action in MVC3

Mohammad Dayyan picture Mohammad Dayyan · Mar 22, 2012 · Viewed 7.8k times · Source

How can we run a method before running each Action in MVC3?

I know we can use the following method for OnActionExecuting :

public class ValidateUserSessionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
      ...
    }
}

But how can we run a method before ActionExecuting ?

Answer

Matthieu picture Matthieu · Mar 22, 2012

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();
      }
   }