可能会有几种
public IActionResult MyAction(DateTime date) { // do something with the date parameter }
public class CustomDateTimeModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); DateTime result;
if (!DateTime.TryParseExact(value.FirstValue, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
{
// return an error if the date is in an incorrect format
bindingContext.ModelState.AddModelError(bindingContext.ModelName, "Invalid date format. The date must be in the format dd/MM/yyyy.");
}
bindingContext.Result = ModelBindingResult.Success(result);
return Task.CompletedTask;
}
}
然后,在控制器中,您需要将参数注释为使用自定义模型绑定器,例如:
public IActionResult MyAction([ModelBinder(BinderType = typeof(CustomDateTimeModelBinder))]DateTime date) { // do something with the date parameter }
这些方法中的一个可能会解决您的问题。