31 lines
1011 B
C#
31 lines
1011 B
C#
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;
|
|
}
|
|
} |