DateTime property not deserializing properly from JSON in Web API

I’m having trouble with date deserialization in my Web API project. Here’s my model class:

public class UserModel
{
    [Required]
    public string LastName { get; set; }

    [Required]
    [DataType(DataType.DateTime)]
    public DateTime DateOfBirth { get; set; }
}

And this is the JSON I’m sending:

{
    "LastName": "Johnson",
    "DateOfBirth": "3/15/1985"
}

String values, boolean fields, and numeric types work fine during model binding, but the DateTime field refuses to bind correctly. I also attempted using the [DataType(DataType.Date)] attribute but that didn’t help either. The date value just comes through as the default DateTime value instead of parsing the JSON string. Has anyone encountered this issue before and found a working solution?

Honestly, just switch to proper ISO format like “1985-03-15T00:00:00Z”. I’ve been burnned by this before - custom converters for every date field turn into a mess fast. Let your frontend handle the formatting instead.

Had this exact headache a few months back. Web API’s default JSON deserializer can’t handle MM/dd/yyyy format reliably. What worked for me was setting up a custom date format in JsonSerializerOptions during startup. In your Program.cs or Startup.cs: csharp services.Configure<JsonOptions>(options => { options.SerializerOptions.Converters.Add(new DateTimeConverter()); }); Then create a converter class for your date format. Or just modify your client code to send dates in ISO format (yyyy-MM-dd) - that’s what most APIs expect anyway. The DataType attribute won’t help since it’s only for MVC validation, not JSON parsing.

I’ve encountered similar issues with date deserialization in Web API. The problem stems from the format of the date string you’re sending. The JSON deserializer typically expects dates in ISO 8601 format, such as “1985-03-15” or “1985-03-15T00:00:00”. The date format “3/15/1985” can be ambiguous and might not be correctly parsed, leading to the default DateTime value. While you could implement a custom JsonConverter for handling DateTime types, I recommend sticking to the ISO format for better compatibility across different systems. As for the DataType attribute, it’s primarily for validation in MVC and has no bearing on JSON deserialization.