Output format of TimeSpan changed in AspNetCore 3.0. For example, if you have below function in both 2.2 and 3.0:
[HttpGet("timespan")]
public TimeSpan Get()
{
return TimeSpan.FromHours(1);
}
For 2.2 application, output would look like below:
"01:00:00"
For 3.0 application, output would look like below:
{
"ticks": 36000000000,
"days": 0,
"hours": 1,
"milliseconds": 0,
"minutes": 0,
"seconds": 0,
"totalDays": 0.041666666666666664,
"totalHours": 1,
"totalMilliseconds": 3600000,
"totalMinutes": 60,
"totalSeconds": 3600
}
Is this change made by design? If so, is there any switch/options we can use to switch between two formats?
Steps to reproduce the behavior:
TimeSpan object (directly or nested) in controller actionsA string can be parsed to TimeSpan directly
/cc @ahsonkhan
You may want to open an issue in https://github.com/dotnet/corefx about System.Json's serialization of TimeSpan
Seems this behavior still exists even if I called .AddNewtonsoftJson() while configuring services. Will try the result of System.Text.Json's serialization.
Looks like it's caused by System.Text.Json.Serialization.JsonSerializer. Result of JsonSerializer.ToString(TimeSpan.FromHours(1)) looks like what it like in 3.0 apps. But I'm still wondering why it's still been handled by System.Text.Json.Serialization.JsonSerializer rather than Json.Net's serializer after calling .AddNewtonsoftJson(), is there any additional step I missed? My dotnet sdk's version is 3.0.100-preview6-012264.
Found one related issue: dotnet/corefx#38641. Maybe adding a customized JsonConverter will be the workaround.
@yhvicey, can you please share a repro project for this particular scenario:
Seems this behavior still exists even if I called .AddNewtonsoftJson() while configuring services. Will try the result of System.Text.Json's serialization.
As for the main issue, please use the referenced issue you've found as it's external to this repo.
Ok I know what happend. I forget to add Microsoft.AspNetCore.Mvc.NewtonsoftJson package to my API project, but it's introduced by Swashbuckle.AspNetCore.SwaggerGen with version 3.0.0-preview3-19153-02. With this specific version, .AddNewtonsoftJson() call won't change anything and it will still use the System.Text.Json. The issue is fixed for me by install the latest version of this package.
Most helpful comment
Ok I know what happend. I forget to add
Microsoft.AspNetCore.Mvc.NewtonsoftJsonpackage to my API project, but it's introduced bySwashbuckle.AspNetCore.SwaggerGenwith version3.0.0-preview3-19153-02. With this specific version,.AddNewtonsoftJson()call won't change anything and it will still use theSystem.Text.Json. The issue is fixed for me by install the latest version of this package.