如果GUID为null,则模型绑定不起作用

时间:2016-10-17 08:24:42

标签: c# asp.net asp.net-web-api model-binding

在以下代码片段中,当我向正文发出POST请求时,ExpenseRecord对象始终为null:public <T> A<T> getA(Class<T> tClass) { // ^^^ ^^^ ^^^ return new A<T>(tClass.newInstance()); // Assumes T has a default constructor }

{"id":null,"name":"Test","reason":"Flight","date":"01.10.2016","amount":10,"text":"Test"}

ExpenseRecord看起来像:

[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);
    }
 }

如果ID设置为正确的fomatted GUID是有效的。但是,在发布新记录时,我不能(或者更不想要)提供ID?

1 个答案:

答案 0 :(得分:1)

正如所说,guid不能为空。

// change
public Guid Id { get; set; }

// to
public Guid? Id { get; set; }

或在POST中发送空guid