代码之家  ›  专栏  ›  技术社区  ›  Richard Szalay

在ActionFilter中更改uiCulture时,数据注释验证消息不本地化。

  •  2
  • Richard Szalay  · 技术社区  · 15 年前

    原因似乎很简单:模型绑定(因此验证)发生在最早的 ActionFilter 方法( OnActionExecuting )执行,因此更改 UICulture 对验证消息没有影响。

    是否有较早的集成点(除了 IHttpModule )我可以在这里用吗?

    我宁愿采用基于属性的方法,因为功能不适用于所有控制器/操作,所以 IHttpModules 听起来不是个好主意(排除筛选列表等)

    2 回复  |  直到 15 年前
        1
  •  1
  •   Çağdaş Tekin    15 年前

    嗯,我能想到的最简单的“基于属性”的解决方案是某种黑客…

    授权过滤器在模型绑定器完成工作之前运行。所以如果你写的是假的 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();
    }
    
        2
  •  0
  •   Community CDub    8 年前

    只是想了另一个解决这个问题的方法。
    我相信这比 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);
    }