So I have a solution with two projects, the main project being MultipleProjectsSwaggerDocs
and then Public
which I added as a reference to the main project. Both of these are ASP.NET Web API (.NET 6)
and I have the main project as the startup project.
I’m trying to setup Swagger so that xml comments that are above the function show in the UI, for instance.
I’ve actually managed to get it to work by following the guide over here.
I then noticed that it wouldn’t show xml comments that I added to Public
, it would only show the comments that were in theMultipleProjectsSwaggerDocs
project.
So after looking around for a while, I noticed that I could just add another options.IncludeXmlComments(...)
and the only problem with that is that I need to hardcode the path to the file that’s generated in the other project.
That won’t work if I were to host the project.
Here is what the Program.cs
looks like for the main project MultipleProjectsSwaggerDocs
builder.Services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo
{
Version = "v1",
Title = "ToDo API",
Description = "An ASP.NET Core Web API for managing ToDo items",
TermsOfService = new Uri("https://example.com/terms"),
Contact = new OpenApiContact
{
Name = "Example Contact",
Url = new Uri("https://example.com/contact")
},
License = new OpenApiLicense
{
Name = "Example License",
Url = new Uri("https://example.com/license")
}
});
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
/* Issue */
options.IncludeXmlComments(@"C:UsersHomePCsourcereposMultipleProjectsSwaggerDocsPublicbinDebugnet6.0Public.xml");
});
As of right now, that works great, it shows the docs for each endpoint.
But as you can see, the path to the other xml file is hardcoded, and that’s not good if I were to host the project, because it wouldn’t find the file. Is there something I can do in order to point it to the second project?
And if this is not the correct way to setup AddSwaggerGen
with two projects in one solution, then what is?
2
Answers
See, it is not necessary to hardcode the full path to the second xml comments file. When you connected the first file, you wrote
Path.Combine(AppContext.BaseDirectory, xmlFilename)
. Nobody forbids you to do the same with the second 🙂For example, I usually use the following code to connect my xml comments to Swagger:
Some theory why this should work
For example, if you open the
PublicPublic.csproj
file, then in my case Rider will generate the following code for me in this file if I add xml comment generation to this project:And when you build a .NET project, all projects linked to it are added as separate dlls to the
binDebugnet6.0
folder of the project you are building. And it works for xml comments too, they will be there too.