如何在我的 ModelBinders 将使用的 asp.net core 中设置区域设置?

问题描述 投票:0回答:1

我试图强制我的 asp.net core 3.1 应用程序使用区域设置“en-US”,无论它运行的 Windows 服务器的默认区域设置如何。

我的主要目标是让 ModelBinding 正确解析用户输入的双精度数。到目前为止,我还没有任何运气。逗号被解释为小数分隔符,而点被解释为千位分隔符,这与 Windows 默认区域设置一致。

所以我的代码看起来(简化)如下:

public class Model
{
    public double Percentage {get; set;}
}

[HttpPost]
public ActionResult Index(Model model)
{
    Debug.WriteLine(model.Percentage);
}

这会导致输入并发布为

"12.34"
的数据被转换为双倍
1234
等。

以前,在 ASP.Net MVC 5 中,将其添加到 web.config 文件中解决了此问题:

  <configuration>
    <system.web>
      <globalization culture="en-US" uiCulture="en-US" />

我尝试了各种方法,我将在下面列出,但没有效果。这些似乎围绕标记的本地化,但不影响模型绑定。

应用与上面列出的相同的设置。 将其添加到

Startup
ConfigureServices()
方法中:

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");

将其添加到相同的方法中:

services.Configure<RequestLocalizationOptions>(
    options =>
    {
        options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
        options.SetDefaultCulture("en-US");
    });

后者的尝试只是尝试和错误。

我尝试在 IIS 和 IIS Express 上运行。

我确实意识到我可以编写一个自定义模型绑定器,但我认为这增加了不必要的复杂性。另外,我可以跳过模型绑定并手动解析发布数据,但实际模型非常广泛并且包含大量数据。我不想走那条路。


附录

我可以使用一个小型演示应用程序重现此行为。重现步骤:

在 Visual Studio .Net 2019 中创建一个新的 Web 应用程序:

  • ASP.Net Core Web 应用程序
  • Web 应用程序(模型-视图-控制器)

添加视图模型:

public class InputModel
{
    [Range(0, 1)]
    public double Fraction { get; set; }
}

将index.cshtml替换为:

@model InputModel
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
    @Html.LabelFor(m=>m.Fraction)
    @Html.TextBoxFor(m=>m.Fraction)
    @Html.ValidationMessageFor(m => m.Fraction)
    <input type="submit" value="Submit" />
}

向控制器添加动作:

[HttpPost]
public IActionResult Index(InputModel input)
{
    if (ModelState.IsValid)
    {
        return Content($"Received fraction: {input.Fraction:E3}");
    }
    return View(input);
}

在我的开发电脑上:

  • 输入0.5无效并且
  • 输入0,5有效。
  • 输入0,1有效,但动作会输出:

收到的分数:1,000E+000

将此添加到 Startup.cs 中的

ConfigureServices

services.Configure<RequestLocalizationOptions>(
    options =>
    {
        options.SupportedCultures = new List<CultureInfo> { new CultureInfo("en-US") };
        options.SupportedUICultures = new List<CultureInfo> { new CultureInfo("en-US") };
        options.SetDefaultCulture("en-US");
    });

没有什么区别。

只有当我通过控制面板 - 时钟和区域 - 更改日期时间或数字格式设置更改设置时,我才能使我的 Web 应用程序接受点作为小数点分隔符。我不喜欢依赖它。

localization model-binding asp.net-core-3.1
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.