Mohammad Dayyan
Mohammad Dayyan

Reputation: 22408

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 ?

Upvotes: 10

Views: 8102

Answers (3)

diegoe
diegoe

Reputation: 256

Also you could consider use Application_BeginRequest method in global.asax

Upvotes: 3

RBZ
RBZ

Reputation: 2074

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

Upvotes: 3

Matthieu
Matthieu

Reputation: 4620

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

Upvotes: 13

Related Questions