[英]Model Binding not working if GUID is null
In the following Code Snippet, the ExpenseRecord object is always null when I make a POST request with the body: {"id":null,"name":"Test","reason":"Flight","date":"01.10.2016","amount":10,"text":"Test"}
在以下代码片段中,当我使用正文发出POST请求时,ExpenseRecord对象始终为null:
{"id":null,"name":"Test","reason":"Flight","date":"01.10.2016","amount":10,"text":"Test"}
[HttpPost]
public IActionResult Post([FromBody]ExpenseRecord record)
{
try
{
this.repository.Create(record);
return this.Created($"api/expenses/{record.Id}", null);
}
catch (ArgumentNullException)
{
return this.BadRequest();
}
catch (InvalidOperationException)
{
return new StatusCodeResult((int)HttpStatusCode.Conflict);
}
}
The ExpenseRecord looks like: ExpenseRecord看起来像:
public class ExpenseRecord : IEquatable<ExpenseRecord>
{
public Guid Id { get; set; }
public string Date { get; set; }
public string Name { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public ExpenseReason Reason { get; set; }
public decimal Amount { get; set; }
public string Text { get; set; }
...
}
If the ID is set to a proper fomatted GUID is works. 如果将ID设置为适当的格式GUID,则可以使用。 However, when posting a new record, I can't (or rather don't want) to provide a ID?
但是,发布新记录时,我不能(或不想)提供ID?
As it was said, a guid can't be null. 如前所述,guid不能为null。
// change
public Guid Id { get; set; }
// to
public Guid? Id { get; set; }
or send an empty guid in your POST 或在您的POST中发送空的Guid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.