c# - Web.API : Unable to set Culture

标签 c# asp.net .net

我在 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 number

我忽略了一个事实,即该值包含在引号中,因此是一个有效的 JSON 字符串。显然,Web API 尝试在模型绑定(bind)期间使用 CultureInfo.InvariantCulture 将字符串转换为数字。有多种方法可以自定义请求如何映射到模型和 using a model binder可能允许您自定义将字符串转换为数字的方式。

关于c# - Web.API : Unable to set Culture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28608009/

相关文章:

html - ASP 菜单 float 属性不起作用

c# - 以编程方式在远程计算机上安装 Windows 服务

c# - 是否可以启动相同的线程?

c# - 计算算法时间

c# - NUnit 是 Selenium 测试的错误选择吗?

c# - 使用 FFmpeg 增加/减少音量

c# - 更新后需要使行处于正常模式

c# - Team Foundation Server 的 "Client"和 "WebApi"库有什么区别?

c# - 在 Xaml 中单击时如何更改按钮内容?

.net - 如何解决 "%1 is not a valid Win32 application"?