首页 > 解决方案 > 卡在 HttpPost 方法上,试图输入 JSON 文本,但对象应该是“空的”

问题描述

我正在尝试使用邮递员将数据发布到数据库,但我要么收到 500 内部服务器错误,要么我的对象为空。

[HttpPost()]
   public IActionResult CreateCustomer([FromBody]CustomerForCreationDto customerInfo)
   {

        var customerError = "Please look at your data and make sure it's not empty, incorrect, or has values that are the same!";
        Customer customer = new Customer();

        // Convert CustomerForCreationDto to Customer entity
        customer.Adress = customerInfo.Adress;
        customer.Name = customerInfo.Name;
        customer.MobileNr = customerInfo.MobileNr;
        customer.CustomerId = customerInfo.CustomerId;
        customer.CreatedAtDate = new DateTime(2011,01,01,12,12,12);
        customer.UpdatedAtDate = customer.CreatedAtDate;

        _customerInfoRepository.AddCustomer(customer);


        if (customerInfo == null)
        {
            return BadRequest(customerError);
        }

        if (customerInfo.Name == customerInfo.Adress || customerInfo.Name == customerInfo.MobileNr || customerInfo.MobileNr == customerInfo.Adress)
        {
            return BadRequest(customerError);
        }


        return CreatedAtRoute("", new { customerId = customer.CustomerId }, customer);
   }    

我不确定出了什么问题。我在邮递员中通过的 JSON 就是这个。

{
"customerId": 5,
"name": "Johnathan",
"adress": "12 Maritz Street, Maryland",
"mobileNr": "0723423789",
"createdAtDate": "2001-10-11T11:12:20",
"updatedAtDate": "2017-08-11T14:13:29"

}

CustomerForCreationDTO

public class CustomerForCreationDto
    {

        public int CustomerId { get; set; }

        [MaxLength(50)]
        public string Name { get; set; }

        [MaxLength(100)]
        public string Adress { get; set; }

        [MaxLength(10)]
        public string MobileNr { get; set; }


        public DateTime CreatedAtDate { get; set; }


        public DateTime UpdatedAtDate  { get; set; }

    }

标签: c#asp.netdatabase

解决方案


尝试将JsonProperty每个模型的属性设置为来自已发布正文的 json 键的相应名称。

从 Nuget 包管理器下载Newtonsoft.json并将命名空间添加到您的模型中,例如 using Newtonsoft.Json;

public class CustomerForCreationDto
{
    [JsonProperty("customerId")]
    public int CustomerId { get; set; }

    [MaxLength(50)]
    [JsonProperty("name")]
    public string Name { get; set; }

    [MaxLength(100)]
    [JsonProperty("adress")]
    public string Adress { get; set; }

    [MaxLength(10)]
    [JsonProperty("mobileNr")]
    public string MobileNr { get; set; }

    [JsonProperty("createdAtDate")]
    public DateTime CreatedAtDate { get; set; }

    [JsonProperty("updatedAtDate")]
    public DateTime UpdatedAtDate { get; set; }
}

推荐阅读