.NET 6中DateOnly类型日期格式解析错误问题求助
.NET 6 API 中 DateOnly 查询参数按挪威格式 dd.MM.yyyy 解析的解决方案
问题说明
在.NET 6 API中使用DateOnly作为查询参数时,已将应用配置为挪威文化(nb-NO,标准日期格式为dd.MM.yyyy),但传递01.04.2024这类日期字符串时,系统错误地按MM.dd.yyyy格式解析为2024年1月4日,而非预期的2024年4月1日。以下是仅针对DateOnly类型的修复方案,无需替换为DateTime。
方案1:局部自定义绑定器(针对单个参数)
创建自定义模型绑定器,强制使用挪威文化解析DateOnly参数:
using Microsoft.AspNetCore.Mvc.ModelBinding; using System.Globalization; public class DateOnlyNorwegianBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext == null) throw new ArgumentNullException(nameof(bindingContext)); var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (valueProviderResult == ValueProviderResult.None) return Task.CompletedTask; bindingContext.ModelState.SetModelValue(bindingContext.ModelName, valueProviderResult); var dateString = valueProviderResult.FirstValue; var norwegianCulture = new CultureInfo("nb-NO"); if (DateOnly.TryParse(dateString, norwegianCulture, DateTimeStyles.None, out var dateOnly)) { bindingContext.Result = ModelBindingResult.Success(dateOnly); } else { bindingContext.ModelState.TryAddModelError( bindingContext.ModelName, $"日期格式错误,请使用挪威标准格式:{norwegianCulture.DateTimeFormat.ShortDatePattern}"); } return Task.CompletedTask; } }
在控制器参数上标记使用该绑定器:
using Microsoft.AspNetCore.Mvc; [HttpGet("data")] public Task<IActionResult> GetData([FromQuery, ModelBinder(BinderType = typeof(DateOnlyNorwegianBinder))] DateOnly date) { return Task.FromResult<IActionResult>(Ok($"Day {date.Day} Month {date.Month} Year {date.Year}")); }
方案2:全局注册绑定器(所有API生效)
如果需要所有DateOnly类型的查询参数都按挪威格式解析,可在Program.cs中全局配置模型绑定提供程序:
builder.Services.AddControllers(options => { options.ModelBinderProviders.Insert(0, new BinderTypeModelBinderProvider(typeof(DateOnlyNorwegianBinder))); });
配置后无需在每个参数上添加ModelBinder属性,全局自动生效。
验证结果
发送请求:http://localhost:7053/data?date=01.04.2024,正确输出应为:
Day 01 Month 04 Year 2024
原因说明
默认的DateOnly模型绑定未正确应用当前配置的文化设置,自定义绑定器通过明确指定挪威文化解析规则,确保日期字符串按dd.MM.yyyy格式转换为DateOnly对象。
内容的提问来源于stack exchange,提问作者Serhat
相关产品推荐
相关产品推荐

