简体   繁体   中英

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

[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:

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. However, when posting a new record, I can't (or rather don't want) to provide a ID?

As it was said, a guid can't be null.

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

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

or send an empty guid in your POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM