OpenAPI docs for models from another assembly

March 29th 2024 OpenAPI ASP.NET Core .NET

By default, the OpenAPI specification created by Swashbuckle for ASP.NET Core web API doesn't include the descriptions for endpoints and models from XML comments. There are step-by-step instructions how to add them in the documentation, but even then there will be no descriptions for models from other assemblies.

To use the descriptions from the XML comments, you need to do the following:

  • Enable the generation of the XML file from the comments during build by adding the following property to the project file:

  • Include XML comments in the generated OpenAPI specification by modifying the SwaggerGenOptions for the AddSwaggerGen:

    builder.Services.AddSwaggerGen(options =>
        var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
            Path.Combine(AppContext.BaseDirectory, xmlFilename));

With these changes, the XML comments for the models and their properties will show up as descriptions in the OpenAPI specification:

Descriptions from XML comments in OpenAPI

Looking at the code above, it's quite obvious what needs to be done to add descriptions from other assemblies. First, enable the XML file generation for that assembly. Then modify the SwaggerGenOptions to include it. To avoid repeating too much code, you can create an array of assemblies to include XML comments for and then loop through it:

builder.Services.AddSwaggerGen(options =>
    Assembly[] assemblies =
    foreach (var assembly in assemblies)
        var xmlFilename = $"{assembly.GetName().Name}.xml";
            Path.Combine(AppContext.BaseDirectory, xmlFilename));

Whenever you need to add XML comments from another assembly, you can now simply add it to the array. You can even move the array at the top of the file to make it easier to find.

Full source code for a working example is available in my GitHub repository.

Including XML comments in OpenAPI specification is pretty straightforward and also well-documented. However, you usually write this code only once when setting up the project. And by the time you add another assembly to your solution with models that are included in the OpenAPI specification, it's likely that you completely forget about it. And then wonder why the descriptions are missing.

Get notified when a new blog post is published (usually every Friday):

If you're looking for online one-on-one mentorship on a related topic, you can find me on Codementor.
If you need a team of experienced software engineers to help you with a project, contact us at Razum.
Creative Commons License