Nguon: Microsoft Learn · .NET 8.0

Hỗ trợ XML documentation comment trong ASP.NET Core OpenAPI

Nguồn: XML doc comment support

ASP.NET Core xử lý XML documentation (tài liệu XML) tự động bằng cách trích xuất các comment trong code để điền vào tài liệu API, đảm bảo code và tài liệu luôn đồng bộ. Metadata từ XML documentation comment được đưa vào tài liệu OpenAPI được tạo ra mà không cần thay đổi code ứng dụng, miễn là project được cấu hình để tạo file XML documentation. XML documentation comment được tự động phát hiện trong assembly của ứng dụng và các assembly được tham chiếu có bật XML documentation.

ASP.NET Core xử lý các XML documentation tag như: <c>, <code>, <list>, <para>, <paramref>, <typeparamref>, <see>, và <seealso>. Với các XML documentation tag tham chiếu đến phần tử khác như <see cref="SomeOtherType">, việc triển khai sẽ loại bỏ XML tag và chuyển tham chiếu thành văn bản thuần túy để đưa vào tài liệu OpenAPI.

Việc xử lý XML documentation trong ASP.NET Core không ảnh hưởng đến hiệu suất runtime (thời gian chạy). Source generator (bộ tạo nguồn) xử lý XML documentation tại compile time (thời gian biên dịch) và lưu cache kết quả, với overhead tối thiểu khi render tài liệu OpenAPI. Hơn nữa, tài liệu OpenAPI có thể được cache lúc runtime bằng output-caching để tối ưu hóa thêm.

Các XML documentation tag được hỗ trợ

Ghi tài liệu phản hồi HTTP

Ghi tài liệu phản hồi HTTP bằng tag <response> và attribute code:

csharp
/// <summary>
/// Retrieves a specific project board by ID.
/// </summary>
/// <param name="id">The ID of the project board to retrieve.</param>
/// <returns>The requested project board.</returns>
/// <response code="200">Returns the requested project board.</response>
/// <response code="404">If the project board is not found.</response>
public static IResult GetProjectBoardById(int id)
{
    var board = Boards.FirstOrDefault(b => b.Id == id);
    if (board == null)
    {
        return Results.NotFound();
    }
    return Results.Ok(board);
}

Thêm ví dụ

Để thêm ví dụ vào tài liệu, dùng tag <example> cho các kiểu hoặc attribute example cho các tham số:

csharp
/// <example>{"name":"Sample","value":42}</example>
/// <param name="id" example="42">The unique identifier</param>

Tùy chỉnh hành vi XML documentation

Bật XML documentation trong project ASP.NET Core API

  1. Bật XML documentation trong file project:

```xml <Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup> <TargetFramework>net10.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <GenerateDocumentationFile>true</GenerateDocumentationFile> </PropertyGroup>

</Project> ```

  1. Dùng phương thức AddOpenApi trong cấu hình service. Không cần cấu hình thêm, source generator sẽ tự xử lý phần còn lại.

```csharp using Api; using Scalar.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenApi();

var app = builder.Build();

if (app.Environment.IsDevelopment()) { app.MapOpenApi(); app.MapScalarApiReference(); }

app.Map("/", () => Results.Redirect("/scalar/v1")); app.MapProjectBoardApis(); app.MapTodoApis();

app.Run(); ```

Source generator phát hiện tất cả các overload chuẩn:

Mỗi overload được chặn để tự động đưa vào XML documentation transformer. Source generator không xử lý các overload khi tham số documentName không phải là biểu thức string literal. Ví dụ, transformer sẽ không được đăng ký trong các tình huống sau:

csharp
var documentName = "v1";
builder.Services.AddOpenApi(documentName); // Không có hỗ trợ XML

Thêm nguồn XML documentation

Package Microsoft.AspNetCore.OpenApi tự động giải quyết XML documentation comment từ:

```xml <Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup> <TargetFramework>net10.0</TargetFramework> <ImplicitUsings>enable</ImplicitUsings> <Nullable>enable</Nullable> <GenerateDocumentationFile>true</GenerateDocumentationFile> </PropertyGroup>

</Project> ```

```xml <Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup> <TargetFramework>net10.0</TargetFramework> <Nullable>enable</Nullable> <ImplicitUsings>enable</ImplicitUsings> <GenerateDocumentationFile>true</GenerateDocumentationFile> </PropertyGroup>

<ItemGroup> <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.3" /> <PackageReference Include="Scalar.AspNetCore" Version="2.0.30" /> </ItemGroup>

<ItemGroup> <ProjectReference Include="..\models\Models.csproj" /> </ItemGroup>

</Project> ```

Việc triển khai phát hiện file XML tĩnh tại compile time. Item group AdditionalFiles chỉ định các nguồn bổ sung cho file XML:

xml
<ItemGroup>
  <PackageReference Include="Some.Package" Version="10.0.0"
                    GeneratePathProperty="true" />
</ItemGroup>

<ItemGroup>
  <AdditionalFiles Include="$(PkgSome_Package)/lib/net10.0/Some.Package.xml" />
</ItemGroup>

Để đưa file XML documentation từ các assembly được tham chiếu vào, thêm chúng như AdditionalFiles trong project:

xml
<ItemGroup>
  <AdditionalFiles Include="Path/To/AssemblyDoc.xml" />
</ItemGroup>

Ví dụ cấu hình để truy cập XML comment cho các kiểu trong assembly Microsoft.AspNetCore.Http:

xml
<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>

Tắt hỗ trợ XML documentation

Để tắt tích hợp XML documentation, xóa source generator khỏi item group Analyzers:

xml
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <GenerateDocumentationFile>true</GenerateDocumentationFile>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.0-preview.2.25161.17" />
    <PackageReference Include="Scalar.AspNetCore" Version="2.0.30" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\models\Models.csproj" />
  </ItemGroup>

  <Target Name="DisableCompileTimeOpenApiXmlGenerator" BeforeTargets="CoreCompile">
    <ItemGroup>
      <Analyzer Remove="$(PkgMicrosoft_AspNetCore_OpenApi)/analyzers/dotnet/cs/Microsoft.AspNetCore.OpenApi.SourceGenerators.dll" />
    </ItemGroup>
  </Target>

</Project>

Triển khai source generator

Tính năng XML documentation được triển khai dưới dạng source generator. Source generator phân tích XML documentation comment tại compile time và chèn code dịch các comment này thành metadata OpenAPI. XmlCommentGenerator trích xuất XML comment từ hai nguồn:

XML comment được parse thành các đối tượng XmlComment có cấu trúc với:

Xử lý các kiểu phức tạp

Xử lý XML comment tạo ra các mô tả OpenApi chính xác và đầy đủ cho nhiều kiểu khác nhau và hỗ trợ các tình huống phức tạp. Nhưng nếu gặp lỗi khi xử lý các kiểu phức tạp, quy trình sẽ bỏ qua kiểu đó một cách khéo léo.

Bằng cách này, các tình huống có thể gây lỗi build giờ đây chỉ dẫn đến thiếu metadata, giúp tránh build failures (lỗi build).

<inheritdoc/>

Generator hỗ trợ tag <inheritdoc>, kế thừa tài liệu miễn là chúng tồn tại trong compilation assembly. Tag <inheritdoc /> chỉ ra rằng các comment phải được giải quyết từ:

Khi <inheritdoc /> được đặt trên một symbol, source generator:

Hành vi giải quyết tự động hiện chỉ khả dụng cho các XML documentation comment tồn tại trong assembly đang được biên dịch, không phải các XML documentation tag trong các project hoặc package được tham chiếu.

XML documentation comment từ ProjectReferences được giải quyết tự động và không cần cấu hình thêm.

Tải và chạy ứng dụng mẫu

Tải sample code (code mẫu) cho bài viết này.

Để chạy mẫu, điều hướng đến thư mục api và nhập dotnet run.

dotnetcli
cd api
dotnet run

Kết quả tương tự sau sẽ hiển thị:

dotnetcli
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

Điều hướng đến http://localhost:5052/ để xem Scalar UI để tương tác với ứng dụng.