使用控制器时,您可以在路由中使用枚举,但必须添加以下内容
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.AspNetCore.Mvc.JsonOptions>(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
控制器示例
public enum Location
{
London
}
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
[HttpGet("{location}")]
public IEnumerable<WeatherForecast> Get(Location location)
{
....
}
}
"parameters": [
{
"name": "location",
"in": "path",
"required": true,
"schema": {
"$ref": "#/components/schemas/Location"
}
}
],
但是当我在最小的 api 中做同样的事情时
public enum Location
{
London
}
app.MapGet("/weatherforecast/{location}", (Location location) =>
{
...
})
.WithName("GetWeatherForecast")
.WithOpenApi();
并添加相同的
builder.Services.ConfigureHttpJsonOptions(options =>
{
options.SerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
builder.Services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
"parameters": [
{
"name": "location",
"in": "path",
"required": true,
"style": "simple",
"schema": {
"type": "string"
}
}
],
有没有办法配置最小的 api 以相同的方式解析路由中的枚举?
最小 api 和控制器的代码可以在这里找到:https://github.com/AnderssonPeter/EnumInPath
您必须添加
[FromRoute]
属性
builder.Services.Configure<Microsoft.AspNetCore.Mvc.JsonOptions>(options =>
{
options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
.......
app.MapGet("/weatherforecast/{location}", ([FromRoute]Location location) =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
Summary.Warm
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();