如何重写ASP.NETWeb应用程序的当前区域性的货币格式设置?

nwlqm0z1  于 5个月前  发布在  .NET
关注(0)|答案(3)|浏览(82)

en-ZA地区的货币小数点和千位分隔符分别是','和' ',但常用的分隔符是'.'表示小数点,加上我的用户想要的','表示千位分隔符。我希望全局设置这些,这样我只需要对所有货币字段使用{0:C}字符串,而无需任何显式的FormatToString调用。
我更希望能够做到这一点,而不改变文化设置的web服务器上,因为我还需要设置小数位的货币为零,作为美分是不想要的估计时,报告的R100 k等,我不想任意设置整个文化为零,只有一个为这个应用程序。
在对this question的回答的评论中,Jon Skeet建议克隆当前的文化和设置,并更改所需的设置。我这样做了:

void Application_Start(object sender, EventArgs e)
{
    var newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
    newCulture.NumberFormat.CurrencyDecimalSeparator = ".";
    newCulture.NumberFormat.CurrencyGroupSeparator = ",";
}

字符串
但是,从现在开始,如何为应用程序处理的所有请求激活新的区域性?是否有其他方法可以实现我希望的操作?

wmtdaxz3

wmtdaxz31#

您可以使用Application_BeginRequest事件为每个请求设置区域性。在事件内部:

var newCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
newCulture.NumberFormat.CurrencyDecimalSeparator = ".";
newCulture.NumberFormat.CurrencyGroupSeparator = ",";

System.Threading.Thread.CurrentThread.CurrentCulture = newCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = newCulture;

字符串

uujelgoq

uujelgoq2#

在问了很多问题并做了很多实验之后,我决定可以肯定地说,唯一的方法是使用从开箱即用控件派生的控件,并使用自定义的culture对象进行自己的格式化。从BoundField派生控件并提供自己的FormatProvider

public class BoundReportField : BoundField
{
    protected virtual string GetDefaultFormatString(FieldFormatTypes formatType)
    {
        var prop = typeof(FormatStrings).GetProperty(formatType.ToString()).GetValue(null, null);
        return prop.ToString();
    }

    protected virtual IFormatProvider GetFormatProvider(FieldFormatTypes formatType)
    {
        var info = (CultureInfo)CultureInfo.CurrentCulture.Clone();
        info.NumberFormat.CurrencyDecimalDigits = 0;
        info.NumberFormat.CurrencySymbol = "R";
        info.NumberFormat.CurrencyGroupSeparator = ",";
        info.NumberFormat.CurrencyDecimalSeparator = ".";
        return info;
    }

    private FieldFormatTypes _formatType;
    public virtual FieldFormatTypes FormatType
    {
        get { return _formatType; }
        set
        {
            _formatType = value;
            DataFormatString = GetDefaultFormatString(value);
        }
    }

    protected override string FormatDataValue(object dataValue, bool encode)
    {
        // TODO Consider the encode flag.
        var formatString = DataFormatString;
        var formatProvider = GetFormatProvider(_formatType);
        if (string.IsNullOrWhiteSpace(formatString))
        {
            formatString = GetDefaultFormatString(_formatType);
        }
        return string.Format(formatProvider, formatString, dataValue);
    }
}

字符串
我将发表一篇文章后与所有血淋淋的细节。

bvk5enib

bvk5enib3#

在将一些“遗留”.NET站点和服务从一个Web服务器迁移到另一个Web服务器时,我遇到了类似的问题。
我最终编写了一个IIS module,以使覆盖主机的货币,数字和日期/时间格式(由主机服务器的区域设置决定),而无需编辑代码。
它允许自定义货币符号,小数点分隔符,数字组分隔符,长日期格式,短日期格式......基本上所有可以通过. NET中的NumberInfo和DateTimeInfo对象显式设置的属性。所有这些都通过web.config文件完成(即:无需更改代码)。
希望这可能会保存一些人的时间和/或挫折。

相关问题