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
orTimeOnly
parameter, or addDateOnly
orTimeOnly
property to a request model. - Send a request to said action, and specify
DateOnly
value as"2021-09-14"
, orTimeOnly
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:
- System.Text.Json.JsonSerializer does not support System.Data.DataTable #41920
- Add
DateOnly
andTimeOnly
string query parameter support aspnetcore#36511
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