如何在Asp.Net Core中设置日期绑定的文化?

我有一个带MVC的Asp.Net Core应用程序。 我正在提交表格上有日期的表格。

表格看起来(大致)像这样:

@model EditCustomerViewModel 

控制器动作是:

 [HttpPost] public async Task Edit(EditCustomerViewModel viewModel) { // do stuff return RedirectToAction("Index"); } 

查看模型是:

 public class EditCustomerViewModel { public Guid Id { get; set; } [DataType(DataType.Date)] public DateTime ServiceStartDate { get; set; } [DataType(DataType.Date)] public DateTime? ServiceEndDate { get; set; } // etc. } 

我在英国,因此日期不是美国格式: dd/MM/YYYY 。 所以默认我提交6/22/2017

在调试期间查看控制器中提交的视图模型时,如果以英国格式提交,则日期为空,但如果使用美国格式则日期为正常。 即22/6/2017给我null ,但22/6/2017必定于正确的日期。

我已经尝试将此添加到Startup.cs但它没有任何区别:

 var supportedCultures = new[] { new CultureInfo("en-GB") }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("en-GB"), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }); CultureInfo.DefaultThreadCurrentCulture = new CultureInfo("en-GB"); CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo("en-GB"); CultureInfo.CurrentCulture = new CultureInfo("en-GB"); CultureInfo.CurrentUICulture = new CultureInfo("en-GB"); 

我已经检查了HTTP标头,并且我发布了正确的标头:

 Accept-Language: en-GB,en 

我究竟做错了什么? 如何告诉MVC Core绑定器以英国格式绑定日期?

ps我在VS2017上使用* .csproj项目文件,目标框架.NetCoreApp 1.1

有几件事。 我不确定你是否可以将新的设置对象推送到这样的中间件(你可能可以),但是大多数时候我看到它在ConfigureServices方法中使用如下:

 public void ConfigureServices(IServiceCollection services) { services.Configure(options => { options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-NZ"); options.SupportedCultures = new List { new CultureInfo("en-US"), new CultureInfo("en-NZ") }; }); services.AddMvc(); } 

第二。 中间件的顺序非常重要。 确保在UseMvc之前调用UseRequestLocalization。 事实上它应该是你的管道中的第一件事,除非有一个特定的原因它不可能。

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseRequestLocalization(); app.UseMvc(); } 

最后,你可以尝试从管道中删除所有提供者(其中一个是cookie提供者。我无法理解为什么你会有这个cookie,但我们只是尝试)。

在您的configure方法中,在RequestCultureProviders列表中调用clear。 这应该确保没有别的东西可以设置文化。

 public void ConfigureServices(IServiceCollection services) { services.Configure(options => { options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("en-GB"); options.SupportedCultures = new List { new CultureInfo("en-GB") }; options.RequestCultureProviders.Clear(); }); services.AddMvc(); } 

更多信息: http : //dotnetcoretutorials.com/2017/06/22/request-culture-asp-net-core/

更新了aspnet core 2.0的答案

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { var supportedCultures = new[] { new CultureInfo("es-CO") }; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("es-CO"), SupportedCultures = supportedCultures, SupportedUICultures = supportedCultures }); // other configurations after (not before) }