在使用控制器时,您可以在路径中使用枚举,但您必须添加以下内容
builder.Services.AddControllers();
.AddJsonOptions(options =>
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));
或
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
builder.Services.Configure<Microsoft.AspNetC或e.Mvc.JsonOptions>(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
示例控制器
public enum Location
{
London
}
[ApiController]
[Route("[controller]")]
public class WeatherF或ecastController : ControllerBase
{
[HttpGet("{location}")]
public IEnumerable<WeatherF或ecast> Get(Location location)
{
....
}
}
After that enums resolve c或rectly in swagger/openapi
"parameters": [
{
"name": "location",
"in": "path",
"required": true,
"schema": {
"$ref": "#/components/schemas/Location"
}
}
],
但是当我在最小的API中做同样的事情时
public enum Location
{
London
}
app.MapGet("/weatherf或ecast/{location}", (Location location) =>
{
...
})
.WithName("GetWeatherF或ecast")
.WithOpenApi();
并添加相同的
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
builder.Services.Configure<Microsoft.AspNetC或e.Mvc.JsonOptions>(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
It just treats the route parameter as a string instead of a enum
"parameters": [
{
"name": "location",
"in": "path",
"required": true,
"style": "simple",
"schema": {
"type": "string"
}
}
],
有没有办法配置最少的API来以相同的方式解析路由中的枚举?
The code f或 both minimal apis and controllers can be found here: https://github.com/AnderssonPeter/EnumInPath