c# - 卡在 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; }
}
解决方案
尝试将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; }
}
推荐阅读
- python - 如何使用 Pandas 找到两个不同日期时间之间的最小值?
- python - 从不立即加载元素的表中抓取数据
- java - 未找到处理 Intent { act=android.settings.LOCALE_SETTINGS } 的 Activity
- python - 有没有办法检查 5 个字符串中的 4 个字符串是否相等?
- mysql-error-1054 - mysql5.7查询多表错误
- linux - 添加 DEFINE_WAIT 无法在 linux 模块中编译
- twitter-bootstrap - 当背景选项为 False 时启用在引导模式外单击
- mysql - nodejs如何在mysql和mongodb之间切换
- python - Pandas 将 datetime.date' 强制转换为 datetime
- python - 如何在终止时执行 Amazon EMR 清理步骤