在运行MVC3中的每个Action之前,我们如何运行一个方法?
我知道我们可以使用以下方法进行OnActionExecuting:
public class ValidateUserSessionFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { ... } }
但是,如何在ActionExecuting之前运行方法?
解决方法
你正在寻找
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(); } }