对于多语言 ASP.NET MVC 3 Web 应用程序,我正在确定Thread.CurrentThread.CurrentCulture
and 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);
}
}
上面的代码已经有将近一年的历史了!所以,我开放征求建议。
我将其注册到 Global.asax 文件中,如下所示:
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;
}
}
全局.asax.cs:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
...
ControllerBuilder.Current.SetControllerFactory(new DefaultControllerFactory(new CultureAwareControllerActivator()));
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)