Search code examples
c#asp.net-core-webapi.net-8.0asp.net-core-8dateonly

The JSON value could not be converted to System.DateOnly with ASP.NET Core 8 Web API


Using .NET 8, I've tried passing in various formats of a date to my API endpoint and I can't get past this error. I get a 400 response with the error:

The JSON value could not be converted to System.DateOnly

My code:

[HttpPost]
public async Task<ActionResult<Item>> CreateItem(CreateItemRequest request)
{
    var Item = await _ItemService.CreateItemAsync(request);

    return Ok(Item);
}

public class CreateItemRequest
{
    ...
    public DateOnly CreateDate { get; set; }
    ...
}

JSON request body:

{
    ...
    "createDate":"2024-1-7"
    ...
}

Solution

  • The model binding with the DateOnly and TimeOnly is available from .NET 7 as mentioned in Add DateOnly and TimeOnly support to model binding & routing.

    The problem is that your provided date string does not match the format. It should be in "yyyy-MM-dd" (ISO 8601) format.

    {
        "createDate":"2024-01-07"
    }