aspnetcore/fundamentals/openapi/openapi-comments.md
ASP.NET Core XML documentation processing extracts code comments automatically to populate API documentation, ensuring the code and documentation remain synchronized. Metadata from XML documentation comments is included in the generated OpenAPI document without requiring changes to the app code, as long as the project is configured to generate the XML documentation file. XML documentation comments are automatically detected in the application assembly and referenced assemblies with XML documentation enabled.
ASP.NET Core processes XML documentation tags like: <c>, <code>, <list>, <para>, <paramref>, <typeparamref>, <see>, and <seealso>. For XML documentation tags that use references to other elements, like <see cref="SomeOtherType">, the implementation strips out the XML tag and maps the reference to plain text for inclusion in the OpenAPI document.
ASP.NET Core XML documentation processing doesn't affect runtime performance. The source generator processes XML documentation at compile time and caches the results, with minimal runtime overhead when rendering the OpenAPI documentation. Furthermore, the OpenAPI document can be cached at runtime using output-caching to further optimize performance.
This article includes a sample app that demonstrates the Microsoft.AspNetCore.OpenApi package's ability to integrate XML documentation comments on types into OpenAPI documents. The sample app is a minimal ASP.NET Core Web API project to generate OpenAPI documents. The XML documentation comments are used to populate summaries, descriptions, parameter information, and response details in the generated OpenAPI document.
The following image shows the Scalar UI with XML documentation comments integrated into the OpenAPI document of the sample app:
Document HTTP responses with the <response> tag and the code attribute:
:::code language="csharp" source="~/fundamentals/openapi/samples/10.x/aspnet-openapi-xml/api/ProjectBoardApis.cs" id="snippet_1" highlight="6-7":::
<!--```csharp /// <response code="200">Success response with data</response> /// <response code="404">Resource not found</response> ```-->To add examples to documentation, use the <example> tag for types or the example attribute for parameters:
/// <example>{"name":"Sample","value":42}</example>
/// <param name="id" example="42">The unique identifier</param>
The following sections describe how to enable and customize XML documentation support.
Enable XML documentation in the project file:
:::code language="xml" source="~/fundamentals/openapi/samples/10.x/aspnet-openapi-xml/models/Models.csproj" highlight="7":::
Use the AddOpenApi method in the service configuration. No configuration is needed, the source generator handles the rest.
:::code language="csharp" source="~/fundamentals/openapi/samples/10.x/aspnet-openapi-xml/api/Program.cs" highlight="6":::
The source generator detects all standard overloads:
Each overload is intercepted to automatically include the XML documentation transformers. The source generator doesn't handle overloads where the documentName parameter isn't a literal string expression. For example, the transformer isn't registered in the following scenarios:
var documentName = "v1";
builder.Services.AddOpenApi(documentName); // No XML support
The Microsoft.AspNetCore.OpenApi NuGet package automatically resolves XML documentation comments from:
The application assembly, when the GenerateDocumentationFile property is set. In the sample app, the API project.
:::code language="xml" source="~/fundamentals/openapi/samples/10.x/aspnet-openapi-xml/models/Models.csproj" highlight="7":::
Any projects referenced via ProjectReferences that have the GenerateDocumentationFile property set. In the sample app, the Models project:
:::code language="xml" source="~/fundamentals/openapi/samples/10.x/aspnet-openapi-xml/api/Api.csproj" highlight="7,16":::
The implementation discovers XML files statically at compile-time. The AdditionalFiles item group specifies additional sources for XML files:
:::code language="xml" source="~/fundamentals/openapi/samples/10.x/aspnet-openapi-xml/api/AdditionalFiles.xml" highlight="7":::
To include XML documentation files from referenced assemblies, add them as AdditionalFiles in the project:
<ItemGroup>
<AdditionalFiles Include="Path/To/AssemblyDoc.xml" />
</ItemGroup>
XML doc comment processing can be configured to access XML comments in other assemblies. This is useful for generating documentation for types that are defined outside the current assembly, such as the ProblemDetails type in the Microsoft.AspNetCore.Http namespace. This configuration is done with directives in the project build file. The following example shows how to configure the XML comment generator to access XML comments for types in the Microsoft.AspNetCore.Http assembly, which includes the ProblemDetails class:
<Target Name="AddOpenApiDependencies" AfterTargets="ResolveReferences">
<ItemGroup>
<AdditionalFiles
Include="@(ReferencePath->'
%(RootDir)%(Directory)%(Filename).xml')"
Condition="'%(ReferencePath.Filename)' ==
'Microsoft.AspNetCore.Http.Abstractions'"
KeepMetadata="Identity;HintPath" />
</ItemGroup>
</Target>
To turn off XML documentation integration, remove the source generator from the Analyzers item group. Removing the source generator prevents it from being used during compilation.
:::code language="xml" source="~/fundamentals/openapi/samples/10.x/aspnet-openapi-xml/api/Api-remove.csproj.xml" highlight="7,19-23":::
<!-- review setting <GenerateDocumentationFile>false</GenerateDocumentationFile> prevents the XML file from being generated. Explain the difference between GenerateDocumentationFile = true and <Analyzer Remove -->The XML documentation feature is implemented as a source generator. The source generator analyzes XML documentation comments at compile time and injects code that translates these comments into OpenAPI metadata. The XmlCommentGenerator extracts XML comments from two sources:
AdditionalFiles via a ParseXmlFile implementation.ParseCompilation implementation.The distinction between these two sources is important. XML documentation files passed as AdditionalFiles are static. XML comments from the target assembly come from Roslyn's <!-- review `XmlDocumentationCommentProvider`--> XML documentation comments provider. The XML documentation comments provider enhances functionality for connecting an XML comment to the compilation symbol's that it's associated with. This has implications for the way <inheritdoc /> resolution happens in the implementation, discussed in the next section.
XML comments are parsed into structured XmlComment objects with:
XML comment processing produces accurate and complete OpenApi descriptions for a wide range of types and supports complex scenarios. But if an error is encountered when processing a complex types, the process bypasses the type gracefully.
In this way, scenarios that might have resulted in build errors now simply result in missing metadata, helping to avoid build failures.
XML documentation comments from referenced assemblies are correctly merged even when their documentation IDs include return type suffixes. As a result, all valid XML comments are reliably included in generated OpenAPI documentation, improving documentation accuracy and completeness for APIs using referenced assemblies.
<inheritdoc/>The generator supports <inheritdoc> tags, which inherit documentation as long as they exist in the compilation assembly. <inheritdoc /> tags indicate that comments must be resolved from:
When <inheritdoc /> is placed on a symbol, The source generator:
The automatic resolution behavior is currently available for XML documentation comments that exist in the assembly under compilation, and not XML documentation tags that are in referenced projects or packages. In the later scenario, XML documentation comments:
XML documentation comments from ProjectReferences are automatically resolved and don't require additional configuration.
<a name="download10"></a>
Download the sample code for this article.
To run the sample, navigate to the api directory and enter dotnet run.
cd api
dotnet run
Output similar to the following is displayed:
Building...
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5052
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: ~/git/aspnet-openapi-xml/api
Navigate to http://localhost:5052/ to view the Scalar UI for interacting with the app. The Scalar UI includes summaries and descriptions on various elements sourced from XML documentation comments.