Your .NET WebApi project is up and running but the SwaggerUI doesn’t show the XML documentation of your code? Here is an easy fix!
The Swagger UI is the standard way of visualizing REST API endpoints of a service. It’s already included in the default template of Visual Studio when creating new WebApi projects. But there is one catch: The XML code documentation is not automatically visible to the user when the service is running.
For .NET6 and higher, there is a simple solution. To fix the issue, you only need to add some lines of code in program.cs
and in your .csproj
file.
Program.cs:
builder.Services.AddSwaggerGen(options =>
{
...
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});
Your WebApi project file:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
These lines publish the documentation and make it accessible for the Swagger UI.
However, your IDE will start reporting missing documentation information for the whole project now. If you don’t want these warnings, add the second line in your project file. It will suppress these warnings.
After adding documentation, your Swagger UI should look like this:
Conclusion
It’s very easy to add documentation to the Swagger UI with just a few lines of code. I am wondering why Microsoft didn’t include this code in its default template since they already provide a well-documented solution for this problem. Maybe, they will change that in a future release.