首页 > 解决方案 > .NET 5 (Core) MVC - 使用 en-GB 的模型绑定 DateTime 不能在 GET 上工作,但在 POST 上工作正常

问题描述

我有一个配置的新 .NET 5 Web 应用程序:

 public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<RequestLocalizationOptions>(
            opts =>
            {
                var supportedCultures = new List<CultureInfo> {new CultureInfo("en-GB"),};

                opts.SupportedCultures = supportedCultures;
                opts.SupportedUICultures = supportedCultures;
                opts.DefaultRequestCulture = new RequestCulture(culture: "en-GB", uiCulture: "en-GB");

            });
        services.AddControllersWithViews();
    }

然后我正在使用:

        app.UseRequestLocalization();
        app.UseRouting();

我的测试表格:

<form method="get" asp-action="TestGet" asp-controller="Home">
    <h2>test get</h2>
     <input type="text" id="From" name="From" value="15/12/2020">
    <button type="submit">go</button>
</form>

<form method="post" asp-action="TestPost" asp-controller="Home">
    <h2>test post</h2>
    <input type="text" id="From" name="From" value="15/12/2020">
    <button type="submit">go</button>
</form>

我的行动:

[HttpGet]
        public RedirectResult TestGet(DateTime from)
        {
            var me = from;
            return Redirect("/");
        }
        
        [HttpPost]
        public RedirectResult TestPost(DateTime from)
        {
            var me = from;
            return Redirect("/");
        }

预期的结果是日期在两种情况下都有约束,但这仅适用于邮寄。在获取日期未设置。

我究竟做错了什么?

标签: .netasp.net-mvc.net-core

解决方案


好的,找到问题了。它的设计是不变的 - 因此允许共享查询字符串。

此处详述问题:https ://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-5.0#globalization-behavior-of-model-binding-route-data-和查询字符串


推荐阅读