C# Swagger生成OpenAPI嵌套类$ref不符合RFC3986,上传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:
- Paste the modified OpenAPI document into Swagger Editor to confirm the error is gone.
- Try uploading the corrected document to Azure API Management again—it should now process without the RFC compliance error.
内容的提问来源于stack exchange,提问作者kenander

