【问题标题】:How to bind null value to model in c# webAPI?如何将空值绑定到 c# webAPI 中的模型?
【发布时间】:2020-09-02 13:10:20
【问题描述】:

我从请求中接收到一个 JSON 并且能够成功绑定到模型,但是当 JSON 中的任何属性的值为 null 时,模型无法绑定。下面是我的代码

 public class JobDetails
        {
            [Required]
            [Range(1, int.MaxValue, ErrorMessage = "TransactionId value must be greater than zero")]
            public int Id { get; set; }        
            public string details{ get; set; }
        } 

    [HttpPost]
    [Route("create/job")]
    public async Task<IActionResult> Add([FromBody]JobDetails model)
    {
      //when i debug model is null. Expected result {Id:null,details:"some data"}
    }

输入json

{Id:null,details:"some data"}

知道如何进行这项工作吗?

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api


    【解决方案1】:

    您可以使用以下属性来忽略空值检查:

     [JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
      public int Id { get; set; } 
    

    【讨论】:

      【解决方案2】:

      尝试将您的 integer 更改为

      public int? Id { get; set; }
      

      接受null

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-12
        • 2023-03-13
        • 1970-01-01
        • 1970-01-01
        • 2013-07-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多