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

Model Binding not working if GUID is null

在下面的代码片段中,当我使用正文发出 POST 请求时,ExpenseRecord 对象始终为空:{"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);
    }
 }

费用记录看起来像:

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

    ...
}

如果将 ID 设置为正确格式化的 GUID 则可以。但是,在发布新记录时,我不能(或者不想)提供 ID?

如前所述,guid 不能为空。

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

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

或者在您的 POST

中发送一个空的 GUID