Swashbuckle实现中缺失#/definitions/HttpError,如何加入Swagger文档?
解决Swagger文档中HttpError定义缺失问题
要让Swagger文档正确识别#/definitions/HttpError的引用,只需在Swagger JSON的根层级definitions节点下添加该类型的具体定义即可,操作步骤如下:
- 定位definitions节点:找到Swagger JSON文件最外层的
"definitions"对象(如果文件中没有这个节点,直接新增即可)。 - 添加HttpError定义:根据业务需求,在
definitions中插入HttpError的结构,示例如下:
"definitions": { // 保留已有的其他定义,比如你的SystemInfoDto "SystemInfoDto": { // 原有的SystemInfoDto结构 }, "HttpError": { "type": "object", "description": "通用HTTP错误响应结构", "properties": { "errorCode": { "type": "integer", "description": "自定义错误码" }, "errorMessage": { "type": "string", "description": "错误提示信息" }, "timestamp": { "type": "string", "format": "date-time", "description": "错误发生时间" } }, "required": ["errorCode", "errorMessage"] } }
- 验证引用有效性:修改完成后,检查所有引用
#/definitions/HttpError的接口响应(比如你提供的/User接口的403、404、409响应),确保Swagger工具不再提示引用缺失。
结合你提供的接口片段,修改后的完整Swagger JSON结构大致如下:
{ // 其他Swagger配置(如swagger版本、info、paths等) "paths": { "/User": { "get": { "tags": ["user"], "summary": "Get the user information", "description": "User", "operationId": "User_Get_GET", "consumes": [], "produces": [ "application/json", "text/json", "text/html", "application/octet-stream", "application/xml", "text/xml" ], "responses": { "200": { "description": "Successfully returns the system information", "schema": { "$ref": "#/definitions/SystemInfoDto" } }, "403": { "description": "Unauthorized", "schema": { "$ref": "#/definitions/HttpError" } }, "404": { "description": "Not Found", "schema": { "$ref": "#/definitions/HttpError" } }, "409": { "description": "Another user has modified this record, please re-retrieve and try again", "schema": { "$ref": "#/definitions/HttpError" } } } } } }, "definitions": { "SystemInfoDto": { // 原有的SystemInfoDto定义 }, "HttpError": { "type": "object", "description": "通用HTTP错误响应结构", "properties": { "errorCode": { "type": "integer", "description": "自定义错误码" }, "errorMessage": { "type": "string", "description": "错误提示信息" }, "timestamp": { "type": "string", "format": "date-time", "description": "错误发生时间" } }, "required": ["errorCode", "errorMessage"] } } }
内容的提问来源于stack exchange,提问作者Sourabh Agrawal
相关产品推荐
相关产品推荐

