在MVC3中的每个Action之前运行一个方法

时间:2012-03-22 20:56:53

标签: c# asp.net asp.net-mvc-3 action-filter

如何在运行MVC3中的每个Action之前运行方法?

我知道我们可以对OnActionExecuting使用以下方法:

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

但是我们怎样才能在ActionExecuting之前运行一个方法?

3 个答案:

答案 0 :(得分:13)

您正在寻找Controller.ExecuteCore()

在每个动作调用之前调用此函数。您可以在控制器或基本控制器中覆盖它。在Nadeem Afana上设置基于Cookie的文化库的示例:

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

答案 1 :(得分:3)

我还建议调查AOP,PostsharpCastle Windsor可以轻松处理任务。

答案 2 :(得分:3)

您也可以考虑在global.asax

中使用Application_BeginRequest方法