Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a method before each Action in MVC3

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 ?

like image 627
Mohammad Dayyan Avatar asked Mar 22 '12 20:03

Mohammad Dayyan


3 Answers

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();
      }
   }
like image 143
Matthieu Avatar answered Oct 08 '22 15:10

Matthieu


I would also suggest looking into AOP, Postsharp or Castle Windsor can easily handle such as task.

like image 22
RBZ Avatar answered Oct 08 '22 14:10

RBZ


Also you could consider use Application_BeginRequest method in global.asax

like image 39
diegoe Avatar answered Oct 08 '22 14:10

diegoe