ModelState validation fails for nullable types

后端 未结 1 1648
一向
一向 2021-01-14 14:53

Can\'t pass ModelState validation in WebApi application for object which contains nullable types and has null values. The error message is \"The value \'null\' is not valid

相关标签:
1条回答
  • 2021-01-14 15:17

    I just did a quick test in one my own WebAPI projects and passing null as a value for a nullable value-type works fine. I suggest you inspect the actual data that is being send to your server using a tool like Fiddler

    Two valid scenarios that will work are:

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

    Scenarios that will NOT work are:

    { 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 
    

    If the two default scenario's do not work then I suspect your problem lies elsewhere. I.e. Have you changed any of the default settings of the JSON serializer in your global.asax?

    0 讨论(0)
提交回复
热议问题