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

时间:2017-08-04 11:53:24

标签: asp.net-mvc swagger swagger-ui

目前我的招摇输出作为一个看起来像这个

的身体参数
      {
        "name": "body",
        "in": "body",
        "description": "",
        "required": true,
        "type": "file"
      }

我读了文档,type属性可以是类型数组

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

但我发现无法告诉aspnet core mvc或swaggerGen输出两种类型?这可能。

我希望swaggerUI包含选择文件或发布一些json数据的选项。可以这样做吗?

enter image description here

1 个答案:

答案 0 :(得分:0)

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

"type": [null,"file"]

This is not valid in OpenAPI/Swagger. type must be a single type, and there's no null type.

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

In OpenAPI/Swagger 2.0 this is not possible – an operation can post either a file or JSON but not both. You'll need two operations - one that accepts JSON, and another one that accepts a file.


What you want will be possible using OpenAPI 3.0. However, I don't know if ASP.NET Core MVC supports OpenAPI 3.0; it may take some time before tools adopt the new version of OpenAPI.

Your API spec (in YAML) would look like this:

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:
        ...