This Q&A question is meant as a helpful references for myself and hopefully for the community. I use Swagger for all my web APIs, and like it to include my source code documentation, as Swagger is to a largely about documentation.
I've long used the following from some example online, but Microsoft.Extensions.PlatformAbstractions is now deprecated, GetTypeInfo requires using System.Reflection;, and the code is overall complex for just getting the path to an XML file:
using Microsoft.Extensions.PlatformAbstractions;
using System.Reflection;
// ...
builder.Services.AddSwaggerGen(options => {
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var fileName = typeof(Program).GetTypeInfo().Assembly.GetName().Name + ".xml";
var xmlPath = Path.Combine(basePath, fileName);
options.IncludeXmlComments(xmlPath);
});
A small readability improvement came later, but requires Microsoft.DotNet.PlatformAbstractions, which was removed.
...
var basePath = ApplicationEnvironment.ApplicationBasePath;
...
I briefly used this slightly shorter code, but it still requires an explicit reference to System.Reflection:
using System.Reflection;
// ...
var xmlFileName = Assembly.GetExecutingAssembly().GetName().Name + ".xml";
Path.Combine(AppContext.BaseDirectory, xmlFileName); // A bit too long to combine into 1 line
builder.Services.AddSwaggerGen(options => { options.IncludeXmlComments(xmlDocsPath); });
While modern .NET has made most programming tasks simpler in my experience than other languages I have used (PHP, Python, Java and C++), this one seems a bit complicated for how common I believe it is.
Is there a simpler way to add XML documentation to Swagger, preferably without hard-coding the program name or use of any reflection?
For future readers: XML files are not generated by default. Search online for how to enable it in your project or with your IDE. For Jetbrains Rider: Open project properties and check the "Generate" box for under Debug and/or Release.
