对于多语言ASP.NET MVC 3 Web应用程序,我在控制器工厂确定Thread.CurrentThread.CurrentCulture和Thread.CurrentThread.CurrentUICulture如下:
public class MyControllerFactory : DefaultControllerFactory { protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext,Type controllerType) { //Get the {language} parameter in the RouteData string UILanguage; if (requestContext.RouteData.Values["language"] == null) UILanguage = "tr"; else UILanguage = requestContext.RouteData.Values["language"].ToString(); //Get the culture info of the language code CultureInfo culture = CultureInfo.CreateSpecificCulture(UILanguage); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; return base.GetControllerInstance(requestContext,controllerType); } }
The above code is nearly a year old now! So,I open for suggestions.
ControllerBuilder.Current.SetControllerFactory(new MyControllerFactory());
这是工作很好,但我不知道这是否是最好的做法和最好的地方做这种类型的行动。
我没有挖掘ControllerFactory的主要作用,我无法与ActionFilterAttribute比较。
你认为做这种类型的行动的最好的地方是什么?
解决方法
我为此使用了一个全局ActionFilter,但最近我意识到,在OnActionExecuting方法中设置当前文化在某些情况下太晚了。例如,当POST请求后的模型到达控制器时,ASP.NET MVC为模型创建元数据。它发生在任何动作被执行之前。因此,DisplayName属性值和其他数据注释东西在这一点使用默认文化处理。
最后,我将设置当前文化移动到自定义IControllerActivator实现,它的工作方式像一个魅力。我想从请求生命周期的角度来看,在自定义控制器工厂中托管这个逻辑几乎是一样的,就像你今天一样。它比使用全局ActionFilter更可靠。
CultureAwareControllerActivator.cs:
public class CultureAwareControllerActivator: IControllerActivator { public IController Create(RequestContext requestContext,Type controllerType) { //Get the {language} parameter in the RouteData string language = requestContext.RouteData.Values["language"] == null ? "tr" : requestContext.RouteData.Values["language"].ToString(); //Get the culture info of the language code CultureInfo culture = CultureInfo.GetCultureInfo(language); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; return DependencyResolver.Current.GetService(controllerType) as IController; } }
Global.asax.cs:
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ... ControllerBuilder.Current.SetControllerFactory(new DefaultControllerFactory(new CultureAwareControllerActivator())); } }