原因似乎很简单:模型绑定(以及验证)在最早的ActionFilter
方法(OnActionExecuting
)执行之前发生,因此更改UICulture
对验证消息没有影响。
我可以在这里使用早期的集成点(IHttpModule
除外)吗?
我宁愿使用基于属性的方法,因为该功能不适用于所有控制器/操作,因此IHttpModules
听起来不是一个好主意(排除过滤器列表等)
答案 0 :(得分:1)
嗯,我能想到的最简单的“基于属性”的解决方案是某种黑客......
授权过滤器在模型绑定器完成其工作之前运行。因此,如果你写一个虚假AuthorizeAttribute
,你可以在那里设置文化。
public class SetCultureAttribute : AuthorizeAttribute {
protected override bool AuthorizeCore(HttpContextBase httpContext) {
//set the culture here
return true; //so the action will get invoked
}
}
//and your action
[SetCulture]
public ActionResult Foo(SomeModel m) {
return View();
}
答案 1 :(得分:0)
想到解决这个问题的另一个解决方案。
我相信这比the other solution更优雅,而且它是基于属性的(虽然这取决于你想如何将这个活页夹附加到你的模型)。
您可以创建自己的模型绑定器并从DataAnnotationsModelBinder
派生它。然后在告诉基类绑定模型之前设置文化。
public class CustomModelBinder : DataAnnotationsModelBinder {
public override object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext) {
//set the culture
return base.BindModel(controllerContext, bindingContext);
}
}
//and the action
public ActionResult Foo([ModelBinder(typeof(CustomModelBinder))]SomeModel m) {
return View();
}
//Or if you don't want that attribute on your model in your actions
//you can attach this binder to your model on Global.asax
protected void Application_Start() {
ModelBinders.Binders.Add(typeof(SomeModel), new CustomModelBinder());
RegisterRoutes(RouteTable.Routes);
}