我在 Web.API 和文化方面遇到了一些问题。
例如(下面更详细的例子)
客户端发送数字:500.000
,它被解释为 five hunderd
而不是 five hundred thousand
。
我在使用 Windows 窗体应用程序
时遇到过这个问题。我将在那里设置线程的区域性
。但是使用 Web.Api(这对我来说是全新的)我需要改变我的策略
。
我的搜索为我提供了几个有希望的解决方案,但到目前为止似乎都没有用。任何人对我有任何指示或可以指出正确的解决方案吗?
使用的一些例子:
解决方案 1: 在webservice的web.config中:提供system.web下的culture
<system.web>
<globalization enableClientBasedCulture="false" culture="nl-BE" uiCulture="nl-BE"/>
</system.web>
解决方案 2: 在我的 Controller 的构造函数中
CultureInfo ci = new CultureInfo("nl-BE");
Thread.CurrentThread.CurrentCulture = ci;
Thread.CurrentThread.CurrentUICulture = ci;
解决方案 3: 编辑 global.asax 使用了提到的解决方案 here但没有骰子。
或
protected void Application_BeginRequest(object sender, EventArgs e)
{
CultureInfo newCulture = (CultureInfo)System.Threading.Thread.CurrentThread.CurrentCulture.Clone();
newCulture.NumberFormat.NumberDecimalSeparator = ",";
newCulture.NumberFormat.NumberGroupSeparator = ".";
Thread.CurrentThread.CurrentCulture = newCulture;
Thread.CurrentThread.CurrentUICulture = newCulture;
}
部分代码:
对象:
public class Book
{
public String Author {get; set;}
public String Title {get; set;}
public Double Price {get; set;}
}
客户端发送的Json:
{ "Author": "User09","Title": "User09 The biography", "Price":"50,39" }
=> With the meaning of 50 euros and 39 cents
函数:
[HttpPost]
public String StoreNewObject(Book myBook)
{
// myBook.Price already contains 5039.0 (as in 5039 euros and 0 cents) here before the first line of code is executed.
...
}
感谢我逐渐减少的耐心。
注意:应用仅限于.Net 4.0
注意 2: 找到一个有效的(丑陋的解决方案) 如下更改我的模型:
public class Book
{
public String Author {get; set;}
public String Title {get; set;}
public String Price {
get { return PriceValue.ToString();
set {
CultureInfo ci = new CultureInfo("nl-BE");
PriceValue = Math.Round(Convert.ToDouble(value, ci),2);
}
}
public Double PriceValue {get; set;}
}
在这种情况下,PriceValue 将包含正确的值。
最佳答案
您的客户端提交的 JSON 不是有效的 JSON。 JSON 基于 JavaScript 语法, float 使用点而不是逗号作为小数点分隔符。来自 json.org :
我忽略了一个事实,即该值包含在引号中,因此是一个有效的 JSON 字符串。显然,Web API 尝试在模型绑定(bind)期间使用 CultureInfo.InvariantCulture
将字符串转换为数字。有多种方法可以自定义请求如何映射到模型和 using a model binder可能允许您自定义将字符串转换为数字的方式。
关于c# - Web.API : Unable to set Culture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28608009/