OpenAPI docs for models from another assembly
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:
<GenerateDocumentationFile>True</GenerateDocumentationFile>
Include XML comments in the generated OpenAPI specification by modifying the
SwaggerGenOptions
for theAddSwaggerGen
:builder.Services.AddSwaggerGen(options => { var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; options.IncludeXmlComments( 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:
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 =
[
Assembly.GetExecutingAssembly(),
typeof(WeatherForecast).Assembly
];
foreach (var assembly in assemblies)
{
var xmlFilename = $"{assembly.GetName().Name}.xml";
options.IncludeXmlComments(
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.