Including Automated Swagger Documentation for API Dependencies

Wed, 25 Jan 2023 19:00 UTC by garethbrown

Swagger can use automated XML documentation produced from .NET code comments to build the swagger.json file that describes an API. Commonly, Swagger / Swashbuckle examples will show configuring in Startup.cs with the following code.

This code looks for an XML file produced for the current executing the assembly, namely your API project.

services.AddSwaggerGen(options =>
{
    // ...
    
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

    options.IncludeXmlComments(xmlPath);

    // ...
});

You will find however that any POCO / model classes from other projects will not be included in the swagger.json file. This is likely because your project is not producing the XML files needed, and if it is, then it may not be looking for them during application start up.

First note that each project for which you want to generate documentation will need the following XML in the .csproj file for that project.

<!-- 
  
Enable XML documentation output (used for automated documentation, e.g Swagger) 
https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-6.0&tabs=visual-studio#xml-comments

-->

<PropertyGroup>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
    <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

Next, update Startup.cs to iterate over assemblies for the current domain and look for the XML documentation file. Change the filter string "ExampleApp.Project." if you need to filter to projects in your solution that your API depends on.

services.AddSwaggerGen(options =>
{
    // ...

    var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.GetName().Name?.StartsWith("ExampleApp.Project.") ?? false);

    foreach (var assembly in assemblies)
    {
        var xmlPath = Path.Combine(AppContext.BaseDirectory, $"{assembly.GetName().Name}.xml");
        if (File.Exists(xmlPath))
        {
            options.IncludeXmlComments(xmlPath);
        }
    }

    // ...
});

Reload your Swagger docs and check for inclusion of comments with the generated documentation.

Ref: Get started with Swashbuckle and ASP.NET Core

UI block loader
One moment please ...