Nguon: Microsoft Learn · .NET 8.0

Sử dụng tài liệu OpenAPI được tạo ra trong ASP.NET Core

Nguồn: Use OpenAPI documents

Sử dụng Swagger UI để kiểm thử ad-hoc cục bộ

Theo mặc định, package Microsoft.AspNetCore.OpenApi không đi kèm với hỗ trợ tích hợp để trực quan hóa hoặc tương tác với tài liệu OpenAPI. Các công cụ phổ biến để trực quan hóa hoặc tương tác với tài liệu OpenAPI bao gồm Swagger UIReDoc. Swagger UI và ReDoc có thể được tích hợp vào ứng dụng theo nhiều cách. Các editor (trình soạn thảo) như Visual Studio và Visual Studio Code cung cấp các extension và trải nghiệm tích hợp để kiểm thử với tài liệu OpenAPI.

Package Swashbuckle.AspNetCore.SwaggerUi cung cấp một bundle web asset của Swagger UI để sử dụng trong các ứng dụng. Package này có thể được dùng để render (hiển thị) UI cho tài liệu được tạo ra. Để cấu hình:

csharp
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder();

builder.Services.AddOpenApi();

var app = builder.Build();

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

    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/openapi/v1.json", "v1");
    });

}

app.MapGet("/", () => "Hello world!");

app.Run();

Như một thực hành bảo mật tốt nhất để hạn chế tiết lộ thông tin, các giao diện người dùng OpenAPI (Swagger UI, ReDoc, Scalar) chỉ nên được bật trong môi trường development (phát triển).

Khởi động ứng dụng và điều hướng đến https://localhost:<port>/swagger để xem Swagger UI.

Để tự động khởi động ứng dụng tại URL Swagger UI sử dụng profile https của Properties/launchSettings.json:

json
"launchBrowser": true,
"launchUrl": "swagger",

Sử dụng Scalar để có tài liệu API tương tác

Scalar là một UI tài liệu tương tác mã nguồn mở cho OpenAPI. Scalar có thể tích hợp với OpenAPI endpoint được cung cấp bởi ASP.NET Core. Để cấu hình Scalar, cài đặt package Scalar.AspNetCore.

csharp
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Scalar.AspNetCore;

var builder = WebApplication.CreateBuilder();

builder.Services.AddOpenApi();

var app = builder.Build();

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

app.MapGet("/", () => "Hello world!");

app.Run();

Khởi động ứng dụng và điều hướng đến https://localhost:<port>/scalar để xem Scalar UI.

Để tự động khởi động ứng dụng tại URL Scalar UI:

json
"launchBrowser": true,
"launchUrl": "scalar",

Lint tài liệu OpenAPI được tạo ra với Spectral

Spectral là một công cụ lint tài liệu OpenAPI mã nguồn mở. Spectral có thể được tích hợp vào quy trình build ứng dụng để xác minh chất lượng của tài liệu OpenAPI được tạo ra. Cài đặt Spectral theo hướng dẫn cài đặt package.

Để tận dụng Spectral để lint tài liệu OpenAPI tại build time (thời gian build), trước tiên cài đặt package Microsoft.Extensions.ApiDescription.Server để bật tạo tài liệu OpenAPI tại build time.

Bật việc tạo tài liệu tại build time bằng cách đặt các thuộc tính sau trong file .csproj của ứng dụng:

xml
<PropertyGroup>
  <OpenApiDocumentsDirectory>$(MSBuildProjectDirectory)</OpenApiDocumentsDirectory>
  <OpenApiGenerateDocuments>true</OpenApiGenerateDocuments>
</PropertyGroup>

Chạy dotnet build để tạo tài liệu.

dotnetcli
dotnet build

Tạo file .spectral.yml với nội dung sau:

text
extends: ["spectral:oas"]

Chạy spectral lint trên file được tạo ra:

dotnetcli
spectral lint WebMinOpenApi.json

Đầu ra hiển thị các vấn đề với tài liệu OpenAPI. Ví dụ:

output
1:1  warning  oas3-api-servers       OpenAPI "servers" must be present and non-empty array.
3:10  warning  info-contact           Info object must have "contact" object.                        info
3:10  warning  info-description       Info "description" must be present and non-empty string.       info
9:13  warning  operation-description  Operation "description" must be present and non-empty string.  paths./.get
9:13  warning  operation-operationId  Operation must have "operationId".                             paths./.get

✖ 5 problems (0 errors, 5 warnings, 0 infos, 0 hints)

Hỗ trợ tiêm IOpenApiDocumentProvider

Tiêm IOpenApiDocumentProvider vào các service để truy cập tài liệu OpenAPI theo chương trình, ngay cả bên ngoài ngữ cảnh HTTP request. Ví dụ sau tùy chỉnh phiên bản 2 ("v2") của tài liệu với thông tin title, version và description:

csharp
using Microsoft.AspNetCore.OpenApi;
using Microsoft.OpenApi;

public class CustomDocumentService(
    [FromKeyedServices("v2")] IOpenApiDocumentProvider documentProvider)
{
    public async Task<OpenApiDocument> GetApiDocumentAsync(
            CancellationToken cancellationToken = default)
    {
        var document = 
            await documentProvider.GetOpenApiDocumentAsync(cancellationToken);

        document.Info = new OpenApiInfo
        {
            Title = "Custom API Title",
            Version = "v2",
            Description = "This is a custom API description for version 2."
        };

        return document;
    }
}

Đăng ký service trong DI container (vùng chứa DI) của bạn. Lưu ý service key phải khớp với tên tài liệu được truyền cho AddOpenApi:

csharp
builder.Services.AddOpenApi(); // Thêm "v1" theo mặc định
builder.Services.AddOpenApi("v2");
builder.Services.AddScoped<CustomDocumentService>();

Tính năng này hỗ trợ các tình huống như tạo client SDK (bộ phát triển phần mềm client), xác thực API contract (hợp đồng API) trong các background process (tiến trình nền), hoặc xuất tài liệu ra các hệ thống bên ngoài.

Hỗ trợ tiêm IOpenApiDocumentProvider được giới thiệu trong ASP.NET Core trong .NET 10.

Ghi chú cho .NET 6, 7, 8

Để tìm hiểu cách sử dụng tài liệu OpenAPI được tạo ra trong Minimal API trong .NET 6, 7, hoặc 8, xem tổng quan về Swagger và NSwag.