对于可空类型,ModelState验证失败

时间:2012-08-12 13:44:11

标签: asp.net-web-api

无法在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
    });
});

2 个答案:

答案 0 :(得分:2)

我刚刚在一个自己的WebAPI项目中进行了快速测试,并将null作为可以为空的值类型的值传递。我建议您使用Fiddler

等工具检查发送到服务器的实际数据

两个有效的方案是:

{ IntProperty: 1, DateProperty: null } 
{ IntProperty: 1 } // Yes, you can simply leave the property out

NOT 工作的场景是:

{ 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序列化程序的任何默认设置?

答案 1 :(得分:0)

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

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

https://stackoverflow.com/a/66712465/908608

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

相关问题