Swagger 按位枚举标志处理

OhW*_*elp 7 c# swagger swagger-ui .net-core openapi

我有一个类似的枚举;

[Flags]
public enum MeteoType : ushort
{
    Wind = 1 << 0,
    Pressure = 1 << 1,
    Temperature = 1 << 2,
    Waves = 1 << 4,
    Currents = 1 << 9,
    Swell = 1 << 13,
    WindWave = 1 << 14,
}
Run Code Online (Sandbox Code Playgroud)

我有一个模型;

public class Params
{
    public List<MeteoType> Meteo { get; set; } = new List<MeteoType>()
    {
        MeteoType.Wind
    };
    ....
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器方法中,我从查询中请求这个模型;

public async Task<IActionResult> Get(int z, int x, int y, [FromQuery] Params parameters)
Run Code Online (Sandbox Code Playgroud)

这让我大摇大摆地看到了这样的观点:

在此输入图像描述

我使用列表是因为它是一个标志,我希望能够选择多个元素。问题从这里开始。当我选择多个元素时,会创建链接,如下所示:

https://localhost:44311?Meteo=1&Meteo=2&Meteo=4&...

而不是

https://localhost:44311?Meteo=7&...

我怎样才能使链接由枚举值的总和生成,而不是全部一一生成?

Hel*_*len 3

OpenAPI 规范不支持按位枚举参数。您的Meteo参数需要在 OpenAPI 定义中进行定义type: integer,即您需要调整注释,以便它们生成type: integer而不是针对type: array此参数。消费者需要手动提供正确的总和值。

# OpenAPI definition generated from the code

openapi: 3.0.0
...

paths:
  /something:
    get:

      parameters:
        - in: query
          name: Meteo
          schema:
            type: integer
          example: 7
          description: >-
            One of the following values, or a sum of multiple values:

             * 1 - Wind
             * 2 - Pressure
             * ...

            For example, 7 means Wind (1) + Pressure (2) + Temperature (4).
Run Code Online (Sandbox Code Playgroud)

或者,您可以尝试分叉Swagger UI并更改代码以将选定的列表值作为单个求和值而不是多值参数发送。