1. 原因
根据[FromBody]Time time
在你的行动中,我猜你正在发送一个有效负载Content-Type
of application/json
。在这种情况下,当收到 json 有效负载时,模型绑定系统将检查参数time
然后尝试为其找到合适的活页夹。因为context.Metadata.ModelType
equals typeof(Time)
而不是typeof(DateTime)
, and 没有自定义 ModelBindertypeof(Time)
, your GetBinder(context)
方法将返回一个null
:
public class DateTimeModelBinderProvider : IModelBinderProvider
{
public IModelBinder GetBinder(ModelBinderProviderContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (context.Metadata.ModelType == typeof(DateTime)) // not typeof(Time)
{
return new BinderTypeModelBinder(typeof(DateTime));
}
return null;
}
}
Thus it 回退到 application/json 的默认模型绑定器。默认的 json 模型绑定器使用Newtonsoft.Json
在引擎盖下,将简单地将整个有效负载反序列化为Time
。结果,你的DateTimeModelBinder
没有被调用。
2. 快速修复
一种方法是使用application/x-www-form-urlencoded
(避免使用application/json
)
去除[FromBody]
属性:
[HttpPost("/test2")]
public IActionResult test2(Time time)
{
return Ok(time);
}
并以以下格式发送有效负载application/x-www-form-urlencoded
POST https://localhost:5001/test2
Content-Type: application/x-www-form-urlencoded
validFrom=2018-01-01&validTo=2018-02-02
现在应该可以了。
3. 使用 JSON
创建一个自定义转换器,如下所示:
public class CustomDateConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public static string[] _formats = new string[] {
"yyyyMMdd", "yyyy-MM-dd", "yyyy/MM/dd"
, "yyyyMMddHHmm", "yyyy-MM-dd HH:mm", "yyyy/MM/dd HH:mm"
, "yyyyMMddHHmmss", "yyyy-MM-dd HH:mm:ss", "yyyy/MM/dd HH:mm:ss"
};
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var dt= reader.Value;
if (DateTime.TryParseExact(dt as string, _formats, new CultureInfo("en-US"), DateTimeStyles.None, out DateTime dateTime))
return dateTime;
else
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value as string);
}
}
我只是复制了您的代码来格式化日期。
更改您的型号如下:
public class Time
{
[ModelBinder(BinderType = typeof(DateTimeModelBinder))]
[JsonConverter(typeof(CustomDateConverter))]
public DateTime? validFrom { get; set; }
[ModelBinder(BinderType = typeof(DateTimeModelBinder))]
[JsonConverter(typeof(CustomDateConverter))]
public DateTime? validTo { get; set; }
}
现在您可以使用以下方式接收时间[FromBody]
[HttpPost("/test")]
public IActionResult test([FromBody]Time time)
{
return Ok(time);
}