Swagger Swashbuckle在swagger.json中未显示响应对象

时间:2019-03-13 15:40:17

标签: swagger asp.net-core-2.1 swagger-2.0 swashbuckle

swagger 2.0。

.netcore 2.1

像图片中的十字花饰。

enter image description here

我在api端点上具有此属性:

[SwaggerResponse(statusCode: 200, type: typeof(List<Cat>), description: "successful operation")]

当我运行API并导航到https://localhost:44394/swagger/v1/swagger.json时,有json,但SwaggerResponse似乎被忽略了。

这是我收到的东西的一个例子:

"/api/data/cats": {
  "get": {
    "tags": [
      "CatApi"
    ],
    "operationId": "GetCatsById",
    "consumes": [],
    "produces": [],
    "parameters": [
      {
        "name": "catIds",
        "in": "query",
        "required": true,
        "type": "array",
        "items": {
          "type": "integer",
          "format": "int32"
        },
        "collectionFormat": "multi",
        "uniqueItems": false
      }
    ],
    "responses": {
      "200": {
        "description": "Success"
      }
    }
  }
},

您可以看到响应仅显示200,但我不确定该从何处获得该描述-正如您在属性中看到的那样,它应该为successful operation,而我的XML注释为{{1 }}。

我很困惑。生成json时,如何使用<response code="200">successful operation</response>属性获取Swashbuckle?

更多信息: 如果我使用SwaggerResponse,那么我会得到想要的东西:

[ProducesResponseType(statusCode: 200, type: typeof(List<Cat>))]

您可以在"/api/data/cats": { "get": { "tags": [ "CatsApi" ], "operationId": "GetCatsById", "consumes": [], "produces": [ "text/plain", "application/json", "text/json" ], "parameters": [ { "name": "catIds", "in": "query", "required": true, "type": "array", "items": { "type": "integer", "format": "int32" }, "collectionFormat": "multi", "uniqueItems": false } ], "responses": { "200": { "description": "Success", "schema": { "uniqueItems": false, "type": "array", "items": { "$ref": "#/definitions/Cat" } } } } } }, 字段中看到其他数据,在produces字段中看到schema

我可以更改为在所有地方都使用responses,但是就Swagger而言,这不是一个标准字段-如果我曾经从Swagger文件中重新生成代码,那么我将必须始终进行这些更改,因此我想与ProducesResponseType一起使用。

2 个答案:

答案 0 :(得分:0)

第1步:仔细检查您是否缺少Swagger Decorator属性,请按照以下步骤操作,并用您的特定Types / MyModel

替换属性

由于您没有设置实际代码,因此要查看其工作原理,请使用默认示例,例如。您可以安装我的Swashbuckle.Examples NuGet软件包。使用下面的新SwaggerResponseExample属性装饰您的方法,您会发现它工作得很好!

// These attributes will help with your nested objects
[SwaggerResponse(HttpStatusCode.OK, Type=typeof(IEnumerable<Country>))]
[SwaggerResponseExample(HttpStatusCode.OK, typeof(CountryExamples))]
[SwaggerResponse(HttpStatusCode.BadRequest, Type = typeof(IEnumerable<ErrorResource>))]
public async Task<HttpResponseMessage> Get(string lang)

第2步:还要确保已将其配置为

configuration
    .EnableSwagger(c =>
    {
        c.OperationFilter<ExamplesOperationFilter>();
    })
    .EnableSwaggerUi();

答案 1 :(得分:0)

还要确保您正确使用注释。我搜索了又搜索,因为 SwaggerResponse 丢失了,我无法理解它。

我以某种方式设法使用了 Nswag Annotations,但需要使用 Swashbucke:

using Swashbuckle.AspNetCore.Annotations;

我认为这是因为我没有安装 SwaggerResponse 的 nuget 并且第一个建议使用这种类型的 nuget 包是 nswag。