【问题标题】:ModelState validation fails for nullable types可空类型的 ModelState 验证失败
【发布时间】:2021-03-20 01:03:34
【问题描述】:

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

【问题讨论】:

    标签: asp.net-web-api


    【解决方案1】:

    我刚刚在我自己的一个 WebAPI 项目中进行了快速测试,并将 null 作为可为 null 值类型的值传递工作正常。我建议您使用 Fiddler 之类的工具检查发送到服务器的实际数据

    两个有效的场景是:

    { 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 
    

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

    【讨论】:

    • 谢谢马丁!问题出在Nightly build packages 我申请了我的项目。 GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore 解决了问题
    • 感谢您提供如此美好的场景 Martin.Vey 有帮助。你能告诉我如果我通过 DateProperty:"" 那么它是否应该忽略为 null 。实际上在我的情况下它忽略为 null 值如果我没记错。
    【解决方案2】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-03-05
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多