Skip to content

Add DateOnly and TimeOnly string body parameter support #59118

Closed

Description

Describe the bug

When using DateOnly or TimeOnly as parts of request body, ASP.NET expects string to be passed, but throws

Serialization and deserialization of 'System.DateOnly'/'System.TimeOnly' instances are not supported and should be avoided.

when it is. Passing DateTime as string (eg. "2021-09-14T21:10:54.798Z") works just fine, so how is DateOnly and TimeOnly less secure?

To Reproduce

  • Create action with DateOnly or TimeOnly parameter, or add DateOnly or TimeOnly property to a request model.
  • Send a request to said action, and specify DateOnly value as "2021-09-14", or TimeOnly value as "10:54" (just random values to demonstrate needed format).

Exceptions (if any)

NotSupportedException mentioned above.

Further technical details

  • ASP.NET Core .NET 6 RC1
  • IDE: VS 2022 Preview 4.0

Related to:

Workaround

https://www.nuget.org/packages/DateOnlyTimeOnly.AspNet/

builder.Services.AddControllers()
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.Converters.Add(new DateOnlyJsonConverter());
            options.JsonSerializerOptions.Converters.Add(new TimeOnlyJsonConverter());
        });

...

public sealed class DateOnlyJsonConverter : JsonConverter<DateOnly>
{
    public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return DateOnly.Parse(reader.GetString()!);
    }

    public override void Write(Utf8JsonWriter writer, DateOnly value, JsonSerializerOptions options)
    {
        var isoDate = value.ToString("O");
        writer.WriteStringValue(isoDate);
    }
}

public sealed class TimeOnlyJsonConverter : JsonConverter<TimeOnly>
{
    public override TimeOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        return TimeOnly.Parse(reader.GetString()!);
    }

    public override void Write(Utf8JsonWriter writer, TimeOnly value, JsonSerializerOptions options)
    {
        var isoTime = value.ToString("O");
        writer.WriteStringValue(isoTime);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions