You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 6 MVC服务器间数字格式化不一致问题求助

解决方案:ASP.NET Core 6 MVC 印尼地区数字格式化不一致问题

1. 视图层面强制指定格式化文化

直接在渲染输入框时显式使用印尼文化(id-ID)进行格式化,彻底脱离服务器系统区域依赖:

@Html.TextBox("Money", string.Format(System.Globalization.CultureInfo.GetCultureInfo("id-ID"), "{0:N}", Model.Money), new { @class = "form-control" })

替代原有的TextBoxFor写法,无论服务器系统默认文化是什么,都会强制用印尼格式渲染数字(千分位用.,小数点用,)。

2. 全局配置应用文化,覆盖服务器默认

完善Program.cs中的请求本地化配置,确保应用全局强制使用印尼文化,且忽略浏览器或请求头传递的文化信息:

var supportedCultures = new[] { "id-ID" };

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture("id-ID"),
    SupportedCultures = supportedCultures,
    SupportedUICultures = supportedCultures,
    // 仅使用默认文化,禁用其他文化获取渠道
    RequestCultureProviders = new List<IRequestCultureProvider>
    {
        new DefaultRequestCultureProvider { DefaultRequestCulture = new RequestCulture("id-ID") }
    }
});

该配置会让应用的所有格式化、模型绑定操作都使用印尼文化,避免服务器系统文化干扰。

3. 模型绑定层面指定解析文化,解决保存异常

服务器2保存时出现155.600变为155,6的问题,是因为模型绑定用了错误的文化解析数字,可通过两种方式修复:

方式A:给模型属性添加DisplayFormat特性

在模型的Money属性上显式指定文化和格式化规则:

using System.ComponentModel.DataAnnotations;
using System.Globalization;

public class YourModel
{
    [DisplayFormat(
        DataFormatString = "{0:N}", 
        ApplyFormatInEditMode = true, 
        Culture = "id-ID"
    )]
    public decimal Money { get; set; }
}

然后视图改用EditorFor渲染,它会自动遵循特性配置:

@Html.EditorFor(m => m.Money, new { htmlAttributes = new { @class = "form-control" } })

方式B:全局配置模型绑定文化

在Program.cs中添加模型绑定的全局文化配置:

builder.Services.Configure<MvcOptions>(options =>
{
    var indonesianCulture = CultureInfo.GetCultureInfo("id-ID");
    // 替换默认的小数模型绑定器,强制使用印尼文化解析
    options.ModelBinderProviders.RemoveType<DecimalModelBinderProvider>();
    options.ModelBinderProviders.Insert(0, new DecimalModelBinderProvider(indonesianCulture));
});

注:DecimalModelBinderProvider需要自定义实现,核心是在绑定过程中用指定文化解析输入字符串。

4. 后续服务器操作建议(若可操作)

若后续能访问服务器2,检查系统区域设置:

  • 打开控制面板 → 区域 → 格式,选择「印度尼西亚」
  • 确认「其他设置」中的数字格式:千分位分隔符为.,小数点为,
  • 重启应用池或服务器,确保设置生效

内容的提问来源于stack exchange,提问作者Another Weeb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:30:56