使用AutoRest生成Net6.0客户端遇InvalidRef错误求助
解决AutoRest生成客户端时的InvalidRef错误
问题原因
第三方API的Swagger文档中引用了#/components/schemas/Microsoft.AspNetCore.JsonPatch.Operations.Operation,但该Schema未在文档的components/schemas节点下定义,导致AutoRest无法解析引用,抛出InvalidRef错误。
解决方法
因为无法修改第三方API,以下是几种无需改动原API的可行方案:
方案1:手动补全本地Swagger文件的缺失Schema
打开本地的swagger_doc.json,找到components.schemas节点,添加缺失的Microsoft.AspNetCore.JsonPatch.Operations.Operation定义(若components节点不存在则先创建):
"components": { "schemas": { // 保留原有Schema,添加以下内容 "Microsoft.AspNetCore.JsonPatch.Operations.Operation": { "type": "object", "properties": { "op": { "type": "string", "enum": ["add", "remove", "replace", "move", "copy", "test"] }, "path": { "type": "string" }, "value": { "type": "object", "additionalProperties": true }, "from": { "type": "string" } }, "required": ["op", "path"] }, // 若后续遇到ProblemDetails的引用错误,可一并添加 "Microsoft.AspNetCore.Mvc.ProblemDetails": { "type": "object", "properties": { "type": { "type": "string" }, "title": { "type": "string" }, "status": { "type": "integer", "format": "int32" }, "detail": { "type": "string" }, "instance": { "type": "string" }, "extensions": { "type": "object", "additionalProperties": true } } } } }
补全后重新运行AutoRest命令即可。
方案2:通过AutoRest自定义配置动态添加Schema
在custom-config.json中添加directive,让AutoRest在处理Swagger时自动注入缺失的Schema,无需修改本地Swagger文件:
{ "directives": [ { "from": "swagger-document", "where": "$.components.schemas", "transform": "return $ || {}; Object.assign($, { 'Microsoft.AspNetCore.JsonPatch.Operations.Operation': { type: 'object', properties: { op: { type: 'string', enum: ['add','remove','replace','move','copy','test'] }, path: { type: 'string' }, value: { type: 'object', additionalProperties: true }, from: { type: 'string' } }, required: ['op', 'path'] } })" } ] }
保持原有AutoRest命令不变,重新执行即可。
方案3:忽略未解析的引用(不推荐)
若暂时不需要严格的类型检查,可在custom-config.json中配置忽略未解析的引用,但生成的对应类型会变为object,不利于后续开发:
{ "modelerfour": { "ignore-unresolved-references": true } }
内容的提问来源于stack exchange,提问作者Dennis Fazekas
相关产品推荐
相关产品推荐

