This commit is contained in:
qianhao.xu
2025-02-21 13:04:44 +08:00
parent f80aca492c
commit 218a1ce86a
8 changed files with 191 additions and 95 deletions

View File

@@ -0,0 +1,31 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
using System.Globalization;
using System.Threading.Tasks;
public class LocalDateModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
var valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult == ValueProviderResult.None)
return Task.CompletedTask;
var dateStr = valueProviderResult.FirstValue;
// 尝试根据特定格式和当前文化信息解析日期字符串
if (DateTime.TryParse(dateStr, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out DateTime parsedDate))
{
bindingContext.Result = ModelBindingResult.Success(parsedDate);
}
else
{
bindingContext.ModelState.TryAddModelError(
bindingContext.ModelName,
"Invalid date format.");
}
return Task.CompletedTask;
}
}

View File

@@ -0,0 +1,15 @@
using Microsoft.AspNetCore.Mvc.ModelBinding;
using System;
public class LocalDateModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context.Metadata.ModelType == typeof(DateTime))
{
return new LocalDateModelBinder();
}
return null;
}
}