Run a method before each Action in MVC3

后端 未结 3 1536
别那么骄傲
别那么骄傲 2021-02-05 23:33

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

I know we can use the following method for OnActionExecuting :

public cla         


        
相关标签:
3条回答
  • 2021-02-06 00:25

    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();
          }
       }
    
    0 讨论(0)
  • 2021-02-06 00:25

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

    0 讨论(0)
  • 2021-02-06 00:34

    Also you could consider use Application_BeginRequest method in global.asax

    0 讨论(0)
提交回复
热议问题