Asp.net web api 可为空的类型的ModelState验证失败

Asp.net web api 可为空的类型的ModelState验证失败,asp.net-web-api,Asp.net Web Api,无法在WebApi应用程序中为包含可空类型且具有空值的对象通过ModelState验证。错误消息为“值'null'对于DateProperty无效。” 对象代码: 公共类TestNull { 公共int属性{get;set;} 公共日期时间?日期属性{get;set;} } 控制器: 公共类TestNullController:ApicController { 公共TestNull Get(int-id) { 返回新的TestNull(){IntProperty=1,DateProperty=

无法在WebApi应用程序中为包含可空类型且具有空值的对象通过ModelState验证。错误消息为“值'null'对于DateProperty无效。”

对象代码:

公共类TestNull
{
公共int属性{get;set;}
公共日期时间?日期属性{get;set;}
}
控制器:

公共类TestNullController:ApicController
{
公共TestNull Get(int-id)
{
返回新的TestNull(){IntProperty=1,DateProperty=null};
}
公共HttpResponseMessage Put(int-id,TestNull值)
{
if(ModelState.IsValid)
返回请求.CreateResponse(HttpStatusCode.OK,值);
其他的
{
var errors=newdictionary();
foreach(ModelState中的var keyValue)
{
errors[keyValue.Key]=keyValue.Value.errors.Select(e=>e.ErrorMessage);
}
返回请求.CreateResponse(HttpStatusCode.BadRequest,错误);
}
}
}
请求:

$.getJSON("api/TestNull/1",
function (data) {
    console.log(data);
    $.ajax({
        url: "api/TestNull/" + data.IntProperty,
        type: 'PUT',
        datatype: 'json',
        data: data
    });
});

我只是在我自己的一个WebAPI项目中做了一个快速测试,并将null作为一个可为null的值类型传递,效果很好。我建议您使用以下工具检查发送到服务器的实际数据:

两种有效的方案将起作用:

{ IntProperty: 1, DateProperty: null } 
{ IntProperty: 1 } // Yes, you can simply leave the property out
{ IntProperty: 1, DateProperty: "null" } // Notice the quotes
{ IntProperty: 1, DateProperty: undefined } // invalid JSON
{ IntProperty: 1, DateProperty: 0 } // Will not be properly interpreted by the .NET JSON Deserializer 
不起作用的场景包括:

{ IntProperty: 1, DateProperty: null } 
{ IntProperty: 1 } // Yes, you can simply leave the property out
{ IntProperty: 1, DateProperty: "null" } // Notice the quotes
{ IntProperty: 1, DateProperty: undefined } // invalid JSON
{ IntProperty: 1, DateProperty: 0 } // Will not be properly interpreted by the .NET JSON Deserializer 

如果这两个默认场景不起作用,那么我怀疑您的问题出在其他地方。也就是说,您是否更改了global.asax中JSON序列化程序的任何默认设置?

将近9年后,我在ASP.NET Core 3.1中仍然遇到类似的问题

但我已经找到了一个可行的解决方法(只需从发送的数据中排除空值,而不是将值作为空值发送)


这不是一个真正的解决方案,因为后端仍然不能正确处理空值,但至少对可空属性的ModelState验证不会失败。

谢谢Martin!问题在于我申请了我的项目。GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling=Newtonsoft.Json.NullValueHandling.Ignore解决了这个问题谢谢你提供了这么好的场景Martin.Vey很有帮助。你能告诉我我是否传递了DateProperty:“那么它是否应该忽略为null。实际上,在我的例子中,如果我没有弄错的话,它是作为null值忽略的。