无法在 WebApi 应用程序中为包含可空类型且具有空值的对象传递 ModelState 验证。错误消息是“值 'null' 对 DateProperty 无效。”
对象代码:
public class TestNull
{
public int IntProperty { get; set; }
public DateTime? DateProperty { get; set; }
}
控制器:
public class TestNullController : ApiController
{
public TestNull Get(int id)
{
return new TestNull() { IntProperty = 1, DateProperty = null };
}
public HttpResponseMessage Put(int id, TestNull value)
{
if(ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.OK, value);
else
{
var errors = new Dictionary<string, IEnumerable<string>>();
foreach (var keyValue in ModelState)
{
errors[keyValue.Key] = keyValue.Value.Errors.Select(e => e.ErrorMessage);
}
return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
}
}
}
要求:
$.getJSON("api/TestNull/1",
function (data) {
console.log(data);
$.ajax({
url: "api/TestNull/" + data.IntProperty,
type: 'PUT',
datatype: 'json',
data: data
});
});