Swashbuckle.AspNetCore
Swashbuckle.AspNetCore copied to clipboard
[Bug]: All enum values show up as "null" when using JSON Source Generation
Describe the bug
When using this setting in the .csproj file:
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
All enum values are null
Expected behavior
Enum values are serialized to integers by default (or strings when using the JSON string enum converter)
Actual behavior
All enum values are null: UI: "Available values : null, null, null"
swagger.json:
"components": {
"schemas": {
"TimeRange": {
"enum": [
null,
null,
null
],
"type": "integer",
"format": "int32"
}
}
}
Steps to reproduce
- Disable reflection based serialization in .csproj:
<JsonSerializerIsReflectionEnabledByDefault>false</JsonSerializerIsReflectionEnabledByDefault>
- create JSON context:
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(TimeRange))]
[JsonSerializable(typeof(IEnumerable<WeatherForecast>))]
internal partial class SourceGenerationContext : JsonSerializerContext
{
}
- Register context in Program.cs:
builder.Services.AddControllers()
.AddJsonOptions(o => o.JsonSerializerOptions.TypeInfoResolverChain.Add(SourceGenerationContext.Default));
- Add Controller with enum URL Parameter:
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet("by-range/{range}")]
public IEnumerable<WeatherForecast> Get(TimeRange range)
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
TemperatureC = Random.Shared.Next(-20, 55)
})
.ToArray();
}
}
public class WeatherForecast
{
public int TemperatureC { get; set; }
}
public enum TimeRange
{
DAILY,
WEEKLY,
MONTHLY
}
Exception(s) (if any)
No response
Swashbuckle.AspNetCore version
7.2.0
.NET Version
8.0.401
Anything else?
No response