gpt4 book ai didi

asp.net-mvc - 使用 ModelBinder 之前更改区域性

转载 作者:行者123 更新时间:2023-12-02 19:57:27 27 4
gpt4 key购买 nike

我想创建一个不同语言的网站。我已经读到我可以创建一个 ActionFilter ,但我有一个小问题:
我必须创建一个自定义 ModelBinder 才能使用英语和德语数字格式(123,456,789.1123.456.789,1)

public class DecimalModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
string key = bindingContext.ModelName;
var v = ((string[])bindingContext.ValueProvider.GetValue(key).RawValue)[0];
float outPut;
if (float.TryParse(v, NumberStyles.Number, System.Globalization.CultureInfo.CurrentCulture, out outPut))
return outPut;
return base.BindModel(controllerContext, bindingContext);

}
}

此 ModelBinder 使用当前区域性来决定使用哪种格式。但不幸的是,在 ActionFilter 改变文化之前就使用了 ModelBinder。

如何在 ModelBinder 激活之前更改文化?

最佳答案

您可以实现 IHttpModule 并在 BeginRequest 中设置区域性,如 here 所示。 .

void context_BeginRequest(object sender, EventArgs e)
{
// eat the cookie (if any) and set the culture
if (HttpContext.Current.Request.Cookies["lang"] != null)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["lang"];
string lang = cookie.Value;
var culture = new System.Globalization.CultureInfo(lang);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
}

关于asp.net-mvc - 使用 ModelBinder 之前更改区域性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13445278/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com