Changing how ASP.NET generates OpenAPI schema names
Tim Deschryver
timdeschryver.dev
By default, ASP.NET generates OpenAPI schema names based on the names of your models. However, there are scenarios where you might want to customize these names to better fit your API design. In my case, to avoid naming conflicts. In this post we'll explore how to change the way ASP.NET generates OpenAPI schema names.
The problem I recently faced involved duplicate model names across different namespaces. For example, I had two classes named ResponseData in separate namespaces: Project.ModuleA.ResponseData and Project.ModuleB.ResponseData. When generating the OpenAPI documentation, both classes were represented as ResponseData, leading to conflicts.
This creates ambiguity in the API documentation and breaks code generation tools that rely on unique schema names.
As an example, take a look the following endpoints, which both return a ResponseData object from different namespaces:
[title="Endpoints.cs"]
varbuilder=WebApplication.CreateBuilder(args);
builder.Services.AddOpenApi();
varapp=builder.Build();
if(app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
app.MapGet("/module-a",()=>newProject.ModuleA.ResponseData("Hello from Module A",100));
app.MapGet("/module-b",()=>newProject.ModuleB.ResponseData("Hello from Module B","Success",67));
app.Run();
The above endpoints generates an OpenAPI document similar to the following one.
Within the components/schemas section, you'll notice that only the last occurence of the ResponseData model is documented, and both endpoints reference the same schema:
This is not what we want. To resolve this, we can customize the schema naming strategy using the CreateSchemaReferenceId option when configuring OpenAPI in ASP.NET.
With this configuration, the CreateSchemaReferenceId method generates schema names that include the full namespace of the model, effectively avoiding naming conflicts. Once you apply this change, the generated OpenAPI document will look like this: