Swagger 2.0。
.netcore 2.1
如图所示。
我在 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 注释是 <response code="200">successful operation</response>
.
我很困惑。我如何获得 Swashbuckle 它使用 SwaggerResponse
生成json时的属性?
更多信息:
如果我使用 [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
字段。
我可以更改为使用ProducesResponseType
无处不在,但就 Swagger 而言,它不是一个标准字段 - 如果我从 swagger 文件重新生成代码,那么我必须始终进行这些更改,所以我想让它与 SwaggerResponse
一起使用.
最佳答案
第 1 步:仔细检查您是否缺少 Swagger 装饰器属性,请按照以下步骤操作,并将属性替换为您的特定类型
/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)
Ste 2:另外确保您已按如下方式配置
configuration
.EnableSwagger(c =>
{
c.OperationFilter<ExamplesOperationFilter>();
})
.EnableSwaggerUi();
关于Swagger Swashbuckle 未在 swagger.json 中显示响应对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55145834/