You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Swagger生成OpenAPI嵌套类$ref不符合RFC3986,上传Azure APIM报错

Fixing "$ref values must be RFC3986-compliant percent-encoded URIs" Error When Uploading OpenAPI to Azure APIM

I've run into this exact issue before with nested classes in auto-generated Swagger/OpenAPI docs—here's how to fix it:

Root Cause

When your Swagger generator processes nested classes (like Namespace.Class.NestedClass), it's using a + character to separate the outer and inner class in the schema reference (e.g., #/components/schemas/Namespace.Class+NestedClass). But per RFC3986, + is a reserved character in URIs (it's used to represent spaces), so it needs to be properly encoded or replaced to be compliant.

Solutions

1. Manually Edit the OpenAPI YAML/JSON

If you just need a quick fix for a single document:

  • Replace all instances of + in your schema references with either:
    • %2B (the RFC-compliant percent-encoded version of +), so your ref becomes:
      $ref: '#/components/schemas/Namespace.Class%2BNestedClass'
      
    • Or replace + with . (a non-reserved character), which is more readable:
      $ref: '#/components/schemas/Namespace.Class.NestedClass'
      
  • After making the changes, re-validate the document in Swagger Editor—this should resolve the error.

2. Configure Your Swagger Generator to Avoid + Altogether

For a long-term fix (so you don't have to edit docs every time), adjust your generator's schema naming rules:

Example for .NET (Swashbuckle)

If you're using Swashbuckle.AspNetCore, add a custom schema ID strategy to replace + with . in your Program.cs or Startup.cs:

services.AddSwaggerGen(c =>
{
    // Replace '+' with '.' in schema IDs for nested classes
    c.CustomSchemaIds(type => type.FullName?.Replace('+', '.'));
});

This will generate schema references like #/components/schemas/Namespace.Class.NestedClass directly, no manual edits needed.

Example for Java (SpringDoc OpenAPI)

For SpringDoc users, you can implement a custom SchemaNameGenerator to replace + in class names with .:

public class CustomSchemaNameGenerator implements SchemaNameGenerator {
    @Override
    public String generateSchemaName(Type type) {
        Class<?> clazz = ResolvedTypeUtils.getRawType(type);
        return clazz.getName().replace('+', '.');
    }
}

// Register the generator in your configuration
@Bean
public OpenAPI customOpenAPI() {
    return new OpenAPI()
        .schemaNameGenerator(new CustomSchemaNameGenerator());
}

3. Verify and Upload to Azure APIM

After applying either fix:

  1. Paste the modified OpenAPI document into Swagger Editor to confirm the error is gone.
  2. Try uploading the corrected document to Azure API Management again—it should now process without the RFC compliance error.

内容的提问来源于stack exchange,提问作者kenander

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 14:57:37