While integrating Swagger in ASP.NET core Web API, if you enable the XML documentation for Web API and if you are using Sub projects(Ex: Model Project), then Swagger UI recognizes only the Web API documentation. It will not fetch the XML comments from the Sub Project. Using the following steps we can include the Sub Projects documentation also in the Swagger.
Using Visual Studio for Windows
- Enable XML documentation for the Sub project.
- In Visual Studio, Right-click the project in Solution Explorer and select Properties
- Check the XML documentation file box under the Output section of the Build tab
- Remove the "bin\Debug" from the path, to get the xml file directly in the Solution folder
- Add the Generated XML file in the Web API as Link
- Right-click on Project -> ADD -> Existing Item
- Browse and Select the file -> Click on dropdown arrow next to ADD button -> Select "Add as Link" (Adding the file as Link, will not copy the file to the project. Instead it will create a link to the Original file and you can see the changes immediately if you modify the original file)
- Open the file properties and Set Copy To Output Directory as "Copy Always"
- Add the following to the services.AddSwaggerGen method under ConfigService method in Startup.cs file
var dir = new DirectoryInfo(AppContext.BaseDirectory); foreach (var fi in dir.EnumerateFiles("*.xml")) { c.IncludeXmlComments(fi.FullName); }
Or you can specify all the files manually as// Adding the xml documentation of the Main project var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); // Adding the xml documentation of the Sub project xmlPath = Path.Combine(AppContext.BaseDirectory, "Scheduling.Model.xml"); c.IncludeXmlComments(xmlPath);
Using Visual Studio Code
- Enable XML documentation for the Subproject by adding the following to .csproj file
$(TargetFramework)\$(MSBuildProjectName).xml - Add the Generated XML file in the Web API as Link and change it's property to Copy Always by adding the following to the Main project .csproj file
Always - Add the following to the services.AddSwaggerGen method under ConfigService method in Startup.cs file
var dir = new DirectoryInfo(AppContext.BaseDirectory); foreach (var fi in dir.EnumerateFiles("*.xml")) { c.IncludeXmlComments(fi.FullName); }
Or you can specify all the files manually as// Adding the xml documentation of the Main project var xmlFile = $"{Assembly.GetEntryAssembly().GetName().Name}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); // Adding the xml documentation of the Sub project xmlPath = Path.Combine(AppContext.BaseDirectory, "Scheduling.Model.xml"); c.IncludeXmlComments(xmlPath);
Happy Coding 😊
Thanks. This really worked.:)
ReplyDelete