如何在 aspnet core mvc 中使用 swagger 为表单主体提供多种数据类型?

How to have multiple data types for form body with swagger in aspnet core mvc?

目前我的 swagger 输出作为主体参数,看起来像这样

      {
        "name": "body",
        "in": "body",
        "description": "",
        "required": true,
        "type": "file"
      }

并且我阅读了文档,类型 属性 可以是类型数组

      {
        "name": "body",
        "in": "body",
        "description": "",
        "required": true,
        "type": [null,"file"]
      }

但我没找到办法告诉aspnet core mvc或swaggerGen输出两种类型?这可能吗

我希望 swaggerUI 包含 select 文件或 post 某些 json 数据的选项。这能做到吗?

and i read the documentation that the type property can be a array of types

"type": [null,"file"]

这在 OpenAPI/Swagger 中无效。 type必须是单一类型,没有null类型。

I would like the swaggerUI to include the option to either select a file or post some json data.

在 OpenAPI/Swagger 2.0 中这是不可能的——一个操作可以 post 一个文件或 JSON 但不能两者兼而有之。您将需要两个操作 - 一个接受 JSON,另一个接受文件。


使用 OpenAPI 3.0 可以实现您想要的。但是,我不知道 ASP.NET Core MVC 是否支持 OpenAPI 3.0;工具采用新版本的 OpenAPI.

可能需要一些时间

您的 API 规范(在 YAML 中)如下所示:

paths:
  /something:
    post:
      requestBody:
        description: Either a file or JSON object
        required: true
        content:

          application/json:
            schema:
              type: object:
              properties:
                ...

          # Post a file via a multipart request
          multipart/form-data:
            schema:
              type: object
              properties:
                file:    # <-- here "file" is a form field name
                  type: string
                  format: binary
              required:
                - file

          # or maybe...
          # Post a file directly
          application/octet-stream:
            schema:
              type: string
              format: binary

      responses:
        ...