Swagger 2.0规范$ref URI合规性问题及模型显示异常求助
问题解决:Swagger 2.0 $ref URI合规性与模型显示问题
错误原因
原错误提示“$ref values must be RFC3986-compliant percent-encoded URIs”是因为定义名称包含[]这类URI特殊字符,这些字符需要进行百分号编码才能在$ref中使用。而直接将#替换为%的操作完全错误,导致$ref无法正确指向定义,所以请求/响应模型只能显示为string类型。
解决方案
方案1:正确编码$ref中的特殊字符
根据RFC3986规范,[需要编码为%5B,]编码为%5D。修改后的$ref写法如下:
responses: '200': description: Returns list of Currencies schema: $ref: '#/definitions/GetResponse%5BList%5BCurrencyModel%5D%5D' '400': description: If an error occur schema: $ref: '#/definitions/GetResponse%5BProducesResponseStub%5D' '404': description: If the list of Currencies is null schema: $ref: '#/definitions/GetResponse%5BProducesResponseStub%5D'
方案2:修改定义名称为合法标识符(推荐)
Swagger定义名称建议使用符合标识符规则的命名(避免特殊字符),既不需要编码,也更易维护。比如把带[]的名称改成驼峰式或下划线分隔的格式:
definitions: GetResponseListCurrencyModel: type: object properties: status: type: boolean data: uniqueItems: false type: array items: $ref: '#/definitions/CurrencyModel' message: type: string GetResponseProducesResponseStub: type: object properties: status: type: boolean data: type: object # 若存在ProducesResponseStub定义,此处添加对应的$ref,否则按需调整结构 message: type: string
对应的$ref同步修改为新名称:
responses: '200': description: Returns list of Currencies schema: $ref: '#/definitions/GetResponseListCurrencyModel' '400': description: If an error occur schema: $ref: '#/definitions/GetResponseProducesResponseStub' '404': description: If the list of Currencies is null schema: $ref: '#/definitions/GetResponseProducesResponseStub'
完整修正后的示例代码
以下是采用方案2的完整Swagger代码:
swagger: '2.0' info: version: v1 title: API contact: name: DEMO paths: /api/Currency/GetCurrencies: get: tags: - Currency summary: Get List of Currencies description: '' operationId: GetAllCurrencies consumes: [] produces: - text/plain - application/json - text/json parameters: [] responses: '200': description: Returns list of Currencies schema: $ref: '#/definitions/GetResponseListCurrencyModel' '400': description: If an error occur schema: $ref: '#/definitions/GetResponseProducesResponseStub' '404': description: If the list of Currencies is null schema: $ref: '#/definitions/GetResponseProducesResponseStub' definitions: GetResponseListCurrencyModel: type: object properties: status: type: boolean data: uniqueItems: false type: array items: $ref: '#/definitions/CurrencyModel' message: type: string GetResponseProducesResponseStub: type: object properties: status: type: boolean data: type: object message: type: string CurrencyModel: type: object properties: id: format: int32 type: integer name: type: string code: type: string currencyUTF32Code: format: int32 type: integer currencySymbol: type: string readOnly: true securityDefinitions: Bearer: name: Authorization in: header type: apiKey description: Please insert JWT with Bearer into field security: - Bearer: []
内容的提问来源于stack exchange,提问作者user2721794
相关产品推荐
相关产品推荐

