【问题标题】:Thread.Culture not being respected for model-binding in MVC2MVC2 中的模型绑定不尊重 Thread.Culture
【发布时间】:2013-06-10 06:48:28
【问题描述】:

为了允许正确绑定特定于文化的值,我有这个 ModelBinder:

public class CultureAwareModelBinder : DefaultModelBinder {

    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {

        BaseController controller = (BaseController)controllerContext.Controller;

        CultureInfo culture  = controller.Settings.Culture;
        CultureInfo language = controller.Settings.Language;

        Thread.CurrentThread.CurrentCulture   = culture;
        Thread.CurrentThread.CurrentUICulture = language;

        return base.BindModel(controllerContext, bindingContext);
    }
}

BaseController.Settings 是一个属性,它为当前应用程序的用户公开正确的CultureInfo)。

我是这样设置的

protected void Application_Start() {
    ModelBinders.Binders.DefaultBinder = new CultureAwareModelBinder();
}

当我调试并单步执行我的代码时,Thread.Culture 设置正确,但是我的模型不断得到错误的值。

这是我的模型:

public class EventModel {

    public DateTime Start { get; set; }
    public DateTime End { get; set; }
}

当我在我的网络浏览器中为任一字段指定“10/6/2013”​​并点击提交时,并且当文化为“en-GB”时(并且我检查了线程的 DateTimeFormat 确实设置为 dd/MM/yyyy) ,MVC 在 2013 年 10 月 6 日而不是 2013 年 6 月 10 日收到它。

我不知道为什么会这样,不幸的是我不能源步进入实际的模型绑定。为什么不尊重线程文化?

【问题讨论】:

    标签: asp.net-mvc model-binding culture


    【解决方案1】:

    在模型活页夹中设置当前文化为时已晚。这应该在执行管道中更早地完成。例如,在您的Global.asax 中的Application_BeginRequest 事件中。

    【讨论】:

    • 文化是每个用户的,Application_BeginRequest 是在 ASP.NET 获得有关当前用户的信息之前,所以我在PostAcquireRequestState 中设置了线程文化,它似乎可以工作。令人失望的是ActionFilters 或 binders 都无法解决这个问题。
    【解决方案2】:

    我遇到了同样的问题。我的解决方案是使用DefaultModelBinder,但是我没有使用ActionFilter 来设置所需的文化,而是使用IAuthorizationFilter,它具有相同的效果,但是在模型绑定之前执行,这与在模型之后执行的“ActionFilter”不同绑定。

    我很欣赏IAuthorizationFilter 的使用有点不雅/不正统,但它成功了。

    【讨论】:

      猜你喜欢
      • 2011-03-29
      • 1970-01-01
      • 2011-03-20
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-10-24
      • 1970-01-01
      • 2011-07-27
      相关资源
      最近更新 更多