ASP.NET Core Web API:如何通过Swagger-Swashbuckle引入依赖DLL的XML注释?
Got it, let's sort this out for you! Here's how you can include XML comments from external DLLs in your ASP.NET Core Web API's Swagger docs using Swashbuckle:
First, make sure each of your class library projects generates an XML comment file:
- Right-click the class library project → Properties → Go to the Build tab
- Under the "Output" section, check the box for XML documentation file
- You can use the default path
$(OutputPath)$(AssemblyName).xmlso the XML file ends up in the same folder as the DLL - Optional: To avoid CS1591 warnings (missing XML comments for public members), go to the Warnings section under Build, find CS1591, and set it to "Warning" or "None" depending on your preference
In your Web API project's Program.cs (or Startup.cs if you're using an older .NET version), update the AddSwaggerGen configuration to include the external XML files:
builder.Services.AddSwaggerGen(c => { // Include XML comments from your Web API project first var currentAssembly = Assembly.GetExecutingAssembly(); var apiXmlPath = Path.Combine(AppContext.BaseDirectory, $"{currentAssembly.GetName().Name}.xml"); c.IncludeXmlComments(apiXmlPath); // Include XML comments from an external library (example: MyExternalLibrary) var externalXmlPath = Path.Combine(AppContext.BaseDirectory, "MyExternalLibrary.xml"); if (File.Exists(externalXmlPath)) { // Set includeControllerXmlComments to false since external libs rarely have controller comments c.IncludeXmlComments(externalXmlPath, includeControllerXmlComments: false); } // Repeat the above block for every external DLL you need to include });
You need the external XML files to be present in your Web API's build/publish directory. There are two easy ways to do this:
Option A: Configure the external library project
Add this to your class library's .csproj file to automatically copy the XML file to any project that references it:
<ItemGroup> <None Update="$(OutputPath)$(AssemblyName).xml"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory> </None> </ItemGroup>
Option B: Manually add the XML file to your Web API project
- Right-click your Web API project → Add → Existing Item
- Navigate to the external library's output folder and select the XML file
- Select the added XML file in Solution Explorer, go to its Properties
- Set Copy to Output Directory to "Copy if newer"
If you're pulling the external library from NuGet, make sure the package includes XML comments. For your own NuGet packages, add this to the library's .csproj to include comments in the package:
<PropertyGroup> <IncludeSymbols>true</IncludeSymbols> <IncludeSource>true</IncludeSource> </PropertyGroup>
This should pull in all the XML comments from your external DLLs into your Swagger docs. Let me know if you hit any snags with specific scenarios!
内容的提问来源于stack exchange,提问作者developer9969

