Changing how ASP.NET generates OpenAPI schema names

profile
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.

Setting up OpenAPI in ASP.NET link

To enable OpenAPI in your ASP.NET application, you add the OpenAPI services and middleware using the AddOpenApi and MapOpenApi methods respectively:

This generates an OpenAPI document that describes your API endpoints and models, which can be accessed at /openapi/v1.json.

Naming Conflicts in OpenAPI Schemas link

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:

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:

Resolving Naming Conflicts using CreateSchemaReferenceId link

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:

Feel free to update this blog post on GitHub, thanks in advance!

Join My Newsletter (WIP)

Join my weekly newsletter to receive my latest blog posts and bits, directly in your inbox.

Support me

I appreciate it if you would support me if have you enjoyed this post and found it useful, thank you in advance.

Buy Me a Coffee at ko-fi.com PayPal logo

Share this post