- Install the package
dotnet add package AspNetCore.Json.SinglePolymorphicResponse
- Adjust your Program.cs and add
builder.Services.AddSinglePolymorphicJsonResponse();
Without this package it is not possible to identify the original response type by discriminator when only a single object is returned. This problem is also open as an issue in the aspnetcore repo, but it looks like that they will fix it only with .NET 8.
[JsonDerivedType(typeof(SummayWeatherForecast), "summary")]
[JsonDerivedType(typeof(ExtendedWeatherForecast), "extended")]
public class WeatherForecast
{
public DateOnly Date { get; set; }
}
public class SummayWeatherForecast : WeatherForecast
{
public string Summary { get; set; }
public SummayWeatherForecast(string summary)
{
Summary = summary;
}
}
public class ExtendedWeatherForecast : SummayWeatherForecast
{
public int TemperatureC { get; set; }
public ExtendedWeatherForecast(string summary) : base(summary)
{
}
}
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet()]
public IEnumerable<WeatherForecast> Get()
{
var forecast1 = new ExtendedWeatherForecast("Freezing") { Date = DateOnly.Parse("2022-11-21"), TemperatureC = -15 };
var forecast2 = new SummayWeatherForecast("Mild") { Date = DateOnly.Parse("2022-11-20") };
return new WeatherForecast[] { forecast1, forecast2 };
}
[HttpGet("Summary")]
public WeatherForecast GetSummary()
{
var forecast2 = new SummayWeatherForecast("Mild") { Date = DateOnly.Parse("2022-11-20") };
return forecast2;
}
[HttpGet("Extended")]
public WeatherForecast GetExtended()
{
var forecast1 = new ExtendedWeatherForecast("Freezing") { Date = DateOnly.Parse("2022-11-21"), TemperatureC = -15 };
return forecast1;
}
}
[
{
"$type": "extended",
"temperatureC": -15,
"summary": "Freezing",
"date": "2022-11-21"
},
{
"$type": "summary",
"summary": "Mild",
"date": "2022-11-20"
}
]
{
"summary": "Mild",
"date": "2022-11-20"
}
{
"temperatureC": -15,
"summary": "Freezing",
"date": "2022-11-21"
}
[
{
"$type": "extended",
"temperatureC": -15,
"summary": "Freezing",
"date": "2022-11-21"
},
{
"$type": "summary",
"summary": "Mild",
"date": "2022-11-20"
}
]
{
"$type": "summary",
"summary": "Mild",
"date": "2022-11-20"
}
{
"$type": "extended",
"temperatureC": -15,
"summary": "Freezing",
"date": "2022-11-21"
}