带外部引用的JSON Schema在线验证正常,C#实现时报无法解析Schema引用错误
问题根因
无参重载的JSchema.Parse(string)方法默认不支持自动发起网络请求解析远程$ref引用,仅能识别本地已加载到内存中的schema定义。在线验证器内置了远程schema拉取、缓存的完整处理逻辑,因此可以正常解析跨地址的引用,本地代码缺失了这部分解析配置,才会触发解析失败异常。
修复方案
- 自定义实现远程schema解析器
内置的默认解析器没有网络拉取能力,需要继承JSchemaResolver抽象类,重写GetSchema方法实现远程schema的拉取逻辑,参考实现:public class RemoteSchemaResolver : JSchemaResolver { // 新增内存缓存,避免重复拉取同一地址的schema private readonly Dictionary<string, JSchema> _schemaCache = new Dictionary<string, JSchema>(); public override JSchema GetSchema(JSchemaReader reader, Uri schemaUri) { // 剥离URI末尾的fragment片段(即#及其后内容),避免请求无效地址 var requestUri = new Uri(schemaUri.GetLeftPart(UriPartial.Path)); var cacheKey = requestUri.AbsoluteUri; // 命中缓存直接返回 if (_schemaCache.TryGetValue(cacheKey, out var cachedSchema)) { return cachedSchema; } // 发起请求拉取远程schema内容 using var webClient = new WebClient(); webClient.Headers.Add("User-Agent", "JsonSchemaValidator"); var schemaContent = webClient.DownloadString(requestUri); // 递归解析远程schema,复用当前的解析器配置 var remoteSchema = JSchema.Parse(schemaContent, new JSchemaReaderSettings { Resolver = this, BaseUri = requestUri }); // 写入缓存 _schemaCache[cacheKey] = remoteSchema; return remoteSchema; } } - 修改根Schema的解析逻辑
替换原来的无参JSchema.Parse调用,传入自定义解析器和根Schema的基地址配置:WebClient wget = new System.Net.WebClient(); Uri schemaUri = new System.Uri(textBox1.Text); var jsonSchema = wget.DownloadString(schemaUri.AbsoluteUri); JObject json = JObject.Parse(textBox3.Text); // 新增解析配置 var parseSettings = new JSchemaReaderSettings { Resolver = new RemoteSchemaResolver(), BaseUri = schemaUri // 传入根Schema的访问地址,用于正确解析相对形式的$ref }; JSchema schema = JSchema.Parse(jsonSchema, parseSettings); // 原有校验逻辑保持不变 IList<ValidationError> errors; bool valid = json.IsValid(schema, out errors); textBox2.Clear(); if (valid == false) { foreach (var err in errors) { textBox2.Text += (err.Path + "\r\n") + (err.Message) + "\r\n"; } } else { textBox2.Text = json.ToString(); } - 常见排查点
- 如果配置完仍然报解析失败,先单独用程序内的WebClient拉取报错对应的远程schema地址,检查是否存在代理拦截、证书校验失败的问题,可根据运行环境给WebClient补充对应代理、证书校验的配置
- 确保被引用的远程Schema本身的格式符合JSON Schema规范,没有内部解析错误
- 部分远程schema地址如果带有相对引用,要保证自定义解析器在加载远程schema时正确传入对应远程地址的基地址,避免相对路径解析错位
内容的提问来源于stack exchange,提问作者Jeff Patton
相关产品推荐
相关产品推荐

