在路由中使用枚举

问题描述 投票:0回答:1

使用控制器时,您可以在路由中使用枚举,但必须添加以下内容

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)
    {
        ....
    }
}

之后枚举在 swagger/openapi 中正确解析

"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

c# swagger openapi swashbuckle minimal-apis
1个回答
0
投票

您必须添加

[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();
© www.soinside.com 2019 - 2024. All rights reserved.