使用 openAPI 文档

使用 Swagger UI 进行本地临时测试

默认情况下,Microsoft.AspNetCore.OpenApi 包不附带用于直观显示 OpenAPI 文档或与之交互的内置支持。 用于可视化或与 OpenAPI 文档交互的常用工具包括 Swagger UIReDoc。 Swagger UI 和 ReDoc 可以通过多种方式集成到应用中。 Visual Studio 和 Visual Studio Code 等编辑器提供了针对 OpenAPI 文档进行测试的扩展和内置体验。

Swashbuckle.AspNetCore.SwaggerUi 包提供了一组 Swagger UI 的 Web 资产,供在应用中使用。 此包可用于呈现生成的文档的 UI。 对此进行配置:

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();

作为限制信息泄露的安全最佳做法, 仅应在开发环境中启用 OpenAPI 用户界面(Swagger UI、ReDoc、Scalar)。 例如,请参阅 Swagger OAuth 2.0 配置

启动应用并导航到 https://localhost:<port>/swagger 查看 Swagger UI。

若要在 Swagger UI URL 处使用配置文件 httpsProperties/launchSettings.json 自动启动应用,请执行以下步骤:

  • 请确认launchBrowser已启用(true)。
  • launchUrl 设置为 swagger
"launchBrowser": true,
"launchUrl": "swagger",

将 Scalar 用于交互式 API 文档

Scalar 是 OpenAPI 的开源交互式文档 UI。 Scalar 可与 ASP.NET Core 提供的 OpenAPI 终结点集成。 若要配置 Scalar,请安装 Scalar.AspNetCore 包。

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();

启动应用程序,并导航到 https://localhost:<port>/scalar 以查看 Scalar 用户界面。

若要使用 httpsProperties/launchSettings.json 配置文件在 Scalar UI URL 自动启动应用,请按以下步骤操作:

  • 请确认launchBrowser已启用(true)。
  • launchUrl 设置为 scalar
"launchBrowser": true,
"launchUrl": "scalar",

使用 Spectral 对生成的 OpenAPI 文档进行 Lint 分析

Spectral 是一个开源的 OpenAPI 文档校验工具。 Spectral 可整合到应用生成中,以验证生成的 OpenAPI 文档的质量。 根据包安装说明安装 Spectral。

若要利用谱在生成时对 OpenAPI 文档进行 linting 处理,请先安装包 Microsoft.Extensions.ApiDescription.Server 以启用生成时 OpenAPI 文档生成。

通过在应用的 .csproj 文件中设置以下属性,在构建时启用文档生成:

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

运行 dotnet build 以生成文档。

dotnet build

创建具有以下内容的 .spectral.yml 文件。

extends: ["spectral:oas"]

对生成的文件运行 spectral lint

spectral lint WebMinOpenApi.json
...

The output shows any issues with the OpenAPI document. For example:

```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)

支持注入 IOpenApiDocumentProvider

你可以通过依赖项注入注入 IOpenApiDocumentProvider 服务,以编程方式访问 OpenAPI 文档,即使在 HTTP 请求上下文之外也是如此。

public class DocumentService
{
    private readonly IOpenApiDocumentProvider _documentProvider;

    public DocumentService(IOpenApiDocumentProvider documentProvider)
    {
        _documentProvider = documentProvider;
    }

    public async Task<OpenApiDocument> GetApiDocumentAsync()
    {
        return await _documentProvider.GetOpenApiDocumentAsync("v1");
    }
}

在 DI 容器中注册服务:

builder.Services.AddScoped<DocumentService>();

这可实现生成客户端 SDK、在后台进程中验证 API 协定或将文档导出到外部系统等方案。

.NET 10 ASP.NET Core 中引入了对注入 IOpenApiDocumentProvider 的支持。 有关详细信息,请参阅 dotnet/aspnetcore #61463

要了解如何在 .NET 6、7 或 8 的最小 API 中使用生成的 OpenAPI 文档,请参阅 Swagger 和 NSwag 概述

使用 Swagger UI 进行本地临时测试

默认情况下,Microsoft.AspNetCore.OpenApi 包不附带用于直观显示 OpenAPI 文档或与之交互的内置支持。 用于可视化或与 OpenAPI 文档交互的常用工具包括 Swagger UIReDoc。 Swagger UI 和 ReDoc 可以通过多种方式集成到应用中。 Visual Studio 和 VS Code 等编辑器提供了针对 OpenAPI 文档进行测试的扩展和内置体验。

Swashbuckle.AspNetCore.SwaggerUi 包提供了一组 Swagger UI 的 Web 资产,供在应用中使用。 此包可用于呈现生成的文档的 UI。 对此进行配置:

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();

作为限制信息泄露的安全最佳做法, 仅应在开发环境中启用 OpenAPI 用户界面(Swagger UI、ReDoc、Scalar)。 例如,请参阅 Swagger OAuth 2.0 配置

启动应用并导航到 https://localhost:<port>/swagger 查看 Swagger UI。

若要在 Swagger UI URL 处使用配置文件 httpsProperties/launchSettings.json 自动启动应用,请执行以下步骤:

  • 请确认launchBrowser已启用(true)。
  • launchUrl 设置为 swagger
"launchBrowser": true,
"launchUrl": "swagger",

将 Scalar 用于交互式 API 文档

Scalar 是 OpenAPI 的开源交互式文档 UI。 Scalar 可与 ASP.NET Core 提供的 OpenAPI 终结点集成。 若要配置 Scalar,请安装 Scalar.AspNetCore 包。

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();

启动应用程序,并导航到 https://localhost:<port>/scalar 以查看 Scalar 用户界面。

若要使用 httpsProperties/launchSettings.json 配置文件在 Scalar UI URL 自动启动应用,请按以下步骤操作:

  • 请确认launchBrowser已启用(true)。
  • launchUrl 设置为 scalar
"launchBrowser": true,
"launchUrl": "scalar",

使用 Spectral 对生成的 OpenAPI 文档进行 Lint 分析

Spectral 是一个开源的 OpenAPI 文档校验工具。 Spectral 可整合到应用生成中,以验证生成的 OpenAPI 文档的质量。 根据包安装说明安装 Spectral。

若要利用 Spectral,请安装 Microsoft.Extensions.ApiDescription.Server 包以启用构建时 OpenAPI 文档生成。

通过在应用的 .csproj 文件中设置以下属性,在构建时启用文档生成:

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

运行 dotnet build 以生成文档。

dotnet build

创建具有以下内容的 .spectral.yml 文件。

extends: ["spectral:oas"]

对生成的文件运行 spectral lint

spectral lint WebMinOpenApi.json
...

The output shows any issues with the OpenAPI document. For example:

```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)