2016-11-23 58 views
0

奇怪的行为在一个MVC项目,我有我的项目是这样的Web.config中设置的变量:Decimal.Parse在Chrome和Firefox

enter image description here

然后在我的代码,我得到的变量,解析它为十进制:

enter image description here

enter image description here

正如你所看到的,这个工作没事,问题是,当我跑我在谷歌Chrome或Mozilla Firefox浏览器的代码,我有diferent结果:

enter image description here

enter image description here

我不已了解为什么发生这种情况,因为并非所有发生在Chrome上运行Web的机器,我能想到的一点是,它似乎是浏览器配置中的一些东西,但它是标准安装,没什么不同。

任何人都可以将我指向正确的方向?或者有什么可以导致这种行为的想法?

UPDATE:

代码文本(我不知道为什么,但确定)

为便于调试我有这样的:

public static decimal ServiceFee 
    { 
     get 
     { 
      var webConfigVar = ConfigurationManager.AppSettings["ServiceFee"]; 
      decimal webConfigVarDecimal = decimal.Parse(webConfigVar ?? "0"); 
      return webConfigVarDecimal; 
     } 
    } 

通常情况下,是这样的

public static decimal ServiceFee 
    { 
     get 
     { 
      return decimal.Parse(ConfigurationManager.AppSettings["ServiceFee"] ?? "0"); 
     } 
    } 

因为Web.config

<appSettings> 
     <add key="ServiceFee" value="0.024" /> 
    </appSettings> 

更新2

我知道,在服务器上运行的代码,但唯一不同的是浏览器,它总是与这些浏览器上几台机器。

如果服务器运行的是无论本地或生产

+1

安置自己的代码** text ** –

+1

另外,C#代码在服务器上运行;应该无所谓浏览器是什么 – BradleyDotNET

回答

3

Decimal.Parse使用当前请求的请求处理线程的CultureInfo,其中ASP.NET可以(虽然不是默认情况下)按设定浏览器的Accept标头 - 以便设置为法语或德语的浏览器将使用其格式规则(其中逗号','是基数位置,而不是点号'.')。这可能是发生了什么事情:您的Chrome浏览器被设置为使用不同的文化。

如果调用任何ParseToString方法(如加载配置文件时),则修复方法是指定CultureInfo.InvariantCulture方法。

这就是为什么静态分析很重要(Visual Studio中的“分析”菜单) - 它可以指出这些错误。

(我个人的看法是,Parse方法应该从.NET中移除,并明确ParseFormatted(IFormatProvider, String)ParseInvariant(String)取代 - 不过这只是我:)

我注意到,效率低下总是打电话Parse你的财产-getter。你应该只是它缓存静态(使用新的C#6.0只读属性语法):

using System.Globalization; 

public static decimal ServiceFee { get; } = 
     Decimal.Parse(
      ConfigurationManager.AppSettings["ServiceFee"] ?? "0", 
      NumberStyles.Number, 
      CultureInfo.InvariantCulture 
     ); 

如果你经常这样做,你可能需要一个可重复使用的方法:

public static Decimal GetAppSettingDecimal(String name) { 

    String textualValue = ConfigurationManager.AppSettings[ name ]; 
    Decimal ret; 
    return Decimal.TryParse(textualValue, NumberStyles.Number, CultureInfo.InvariantCulture, out ret) ? ret : 0; 
} 

public static Decimal ServiceFee { get; } = GetAppSettingDecimal("ServiceFee"); 
+0

完美的人!刚刚好。我会考虑这个建议。谢啦。 –