Swashbuckle 和 ASP.NET Core 入门

注意

在 .NET 8 及更高版本中,不支持使用 Swashbuckle 在构建时生成 OpenAPI 文档。 有关受支持的构建时替代方法,请参阅使用 Swagger / OpenAPI 的 ASP.NET Core Web API 文档。 .NET 8 仍支持运行时文档生成。

Swashbuckle 有三个主要组成部分:

  • Swashbuckle.AspNetCore.Swagger:将 SwaggerDocument 对象公开为 JSON 终结点的 Swagger 对象模型和中间件。

  • Swashbuckle.AspNetCore.SwaggerGen:从路由、控制器和模型直接生成 SwaggerDocument 对象的 Swagger 生成器。 它通常与 Swagger 终结点中间件结合,以自动公开 Swagger JSON。

  • Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的嵌入式版本。 它解释 Swagger JSON 以构建描述 Web API 功能的可自定义的丰富体验。 它包括针对公共方法的内置测试工具。

包安装

可以使用以下方法来添加 Swashbuckle:

  • 从“程序包管理器控制台”窗口:

    • 转到“视图”>“其他窗口”>“程序包管理器控制台”

    • 导航到包含 .csproj 文件的目录

    • 请执行以下命令:

      Install-Package Swashbuckle.AspNetCore -Version 6.5.0
      
  • 从“管理 NuGet 程序包”对话框中:

    • 右键单击“解决方案资源管理器”>“管理 NuGet 包”中的项目
    • 将“包源”设置为“nuget.org”
    • 确保启用“包括预发行版”选项
    • 在搜索框中输入“Swashbuckle.AspNetCore”
    • 从“浏览”选项卡中选择最新的“Swashbuckle.AspNetCore”包,然后单击“安装”

添加并配置 Swagger 中间件

将 Swagger 生成器添加到 Program.cs 中的服务集合:

builder.Services.AddControllers();

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

只有最小 API 才需要调用上一示例中显示的 AddEndpointsApiExplorer。 有关详细信息,请参阅此 StackOverflow 帖子

此外,在 Program.cs 中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务:

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

仅当将当前环境设置为“开发”时,上述代码才会添加 Swagger 中间件。 UseSwaggerUI 方法调用会启用 Swagger UI 工具的嵌入版本。

启动应用,并导航到 https://localhost:<port>/swagger/v1/swagger.json。 生成的描述终结点的文档显示在 OpenAPI 规范 (openapi.json) 中。

可在 https://localhost:<port>/swagger 找到 Swagger UI。 通过 Swagger UI 浏览 API,并将其合并其他计划中。

提示

要在应用的根 (https://localhost:<port>/) 处提供 Swagger UI,请将 RoutePrefix 属性设置为空字符串:

app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
    options.RoutePrefix = string.Empty;
});

如果使用目录及 IIS 或反向代理,请使用 ./ 前缀将 Swagger 终结点设置为相对路径。 例如 ./swagger/v1/swagger.json。 使用 /swagger/v1/swagger.json 指示应用在 URL 的真实根目录中查找 JSON 文件(如果使用,加上路由前缀)。 例如,请使用 https://localhost:<port>/<route_prefix>/swagger/v1/swagger.json 而不是 https://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json

注意

默认情况下,Swashbuckle 会在 3.0 版规范(官方称为 OpenAPI 规范)中生成并公开 Swagger JSON。 为了支持向后兼容性,可以改为选择以 2.0 格式公开 JSON。 对于当前支持 OpenAPI 版本 2.0 的 Microsoft Power Apps 和 Microsoft Flow 等集成,此 2.0 格式非常重要。 若要选择采用 2.0 格式,请在 Program.cs 中设置 SerializeAsV2 属性:

app.UseSwagger(options =>
{
    options.SerializeAsV2 = true;
});

自定义和扩展

Swagger 提供了为对象模型进行归档和自定义 UI 以匹配你的主题的选项。

API 信息和说明

传递给 AddSwaggerGen 方法的配置操作会添加诸如作者、许可证和说明的信息。

Program.cs 中,导入以下命名空间以使用 OpenApiInfo 类:

using Microsoft.OpenApi.Models;

使用 OpenApiInfo 类修改 UI 中显示的信息:

builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "ToDo API",
        Description = "An ASP.NET Core Web API for managing ToDo items",
        TermsOfService = new Uri("https://example.com/terms"),
        Contact = new OpenApiContact
        {
            Name = "Example Contact",
            Url = new Uri("https://example.com/contact")
        },
        License = new OpenApiLicense
        {
            Name = "Example License",
            Url = new Uri("https://example.com/license")
        }
    });
});

Swagger UI 显示版本的信息:

Swagger UI with version information: description, author, and license.

XML 注释

可使用以下方法启用 XML 注释:

  • 在解决方案资源管理器中右键单击该项目,然后选择“Edit <project_name>.csproj”。
  • GenerateDocumentationFile 添加到 .csproj 文件:
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

启用 XML 注释,为未记录的公共类型和成员提供调试信息。 警告消息指示未记录的类型和成员。 例如,以下消息指示违反警告代码 1591:

warning CS1591: Missing XML comment for publicly visible type or member 'TodoController'

要在项目范围内取消警告,请定义要在项目文件中忽略的以分号分隔的警告代码列表。 将警告代码追加到 $(NoWarn); 也会应用 C# 默认值

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

要仅针对特定成员取消警告,请将代码附入 #pragma warning 预处理程序指令中。 此方法对于不应通过 API 文档公开的代码非常有用。在以下示例中,将忽略整个 TodoContext 类的警告代码 CS1591。 在类定义结束时还原警告代码的强制执行。 使用逗号分隔的列表指定多个警告代码。

namespace SwashbuckleSample.Models;

#pragma warning disable CS1591
public class TodoContext : DbContext
{
    public TodoContext(DbContextOptions<TodoContext> options) : base(options) { }

    public DbSet<TodoItem> TodoItems => Set<TodoItem>();
}
#pragma warning restore CS1591

将 Swagger 配置为使用按照上述说明生成的 XML 文件。 对于 Linux 或非 Windows 操作系统,文件名和路径区分大小写。 例如,TodoApi.XML 文件在 Windows 上有效,但在 CentOS 上无效。

builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "ToDo API",
        Description = "An ASP.NET Core Web API for managing ToDo items",
        TermsOfService = new Uri("https://example.com/terms"),
        Contact = new OpenApiContact
        {
            Name = "Example Contact",
            Url = new Uri("https://example.com/contact")
        },
        License = new OpenApiLicense
        {
            Name = "Example License",
            Url = new Uri("https://example.com/license")
        }
    });

    // using System.Reflection;
    var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    options.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});

在上述代码中,反射用于生成与 Web API 项目相匹配的 XML 文件名。 AppContext.BaseDirectory属性用于构造 XML 文件的路径。 一些 Swagger 功能(例如,输入参数的架构,或各自属性中的 HTTP 方法和响应代码)无需使用 XML 文档文件即可起作用。 对于大多数功能(即方法摘要以及参数说明和响应代码说明),必须使用 XML 文件。

通过向节标题添加说明,将三斜杠注释添加到操作增强了 Swagger UI。 执行 Delete 操作前添加 <summary> 元素:

/// <summary>
/// Deletes a specific TodoItem.
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(long id)
{
    var item = await _context.TodoItems.FindAsync(id);

    if (item is null)
    {
        return NotFound();
    }

    _context.TodoItems.Remove(item);
    await _context.SaveChangesAsync();

    return NoContent();
}

Swagger UI 显示上述代码的 <summary> 元素的内部文本:

Swagger UI showing XML comment 'Deletes a specific TodoItem.' for the DELETE method.

生成的 JSON 架构驱动 UI:

"delete": {
    "tags": [
        "Todo"
    ],
    "summary": "Deletes a specific TodoItem.",
    "parameters": [
        {
            "name": "id",
            "in": "path",
            "description": "",
            "required": true,
            "schema": {
                "type": "integer",
                "format": "int64"
            }
        }
    ],
    "responses": {
        "200": {
            "description": "Success"
        }
    }
},

<remarks> 元素添加到 Create 操作方法文档。 它可以补充 <summary> 元素中指定的信息,并提供更可靠的 Swagger UI。 <remarks> 元素内容可包含文本、JSON 或 XML。

/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <remarks>
/// Sample request:
///
///     POST /Todo
///     {
///        "id": 1,
///        "name": "Item #1",
///        "isComplete": true
///     }
///
/// </remarks>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(Get), new { id = item.Id }, item);
}

请注意带这些附加注释的 UI 增强功能:

Swagger UI with additional comments shown.

数据注释

使用 System.ComponentModel.DataAnnotations 命名空间中找到的属性来标记模型,以帮助驱动 Swagger UI 组件。

[Required] 属性添加到 TodoItem 类的 Name 属性:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace SwashbuckleSample.Models;

public class TodoItem
{
    public long Id { get; set; }

    [Required]
    public string Name { get; set; } = null!;

    [DefaultValue(false)]
    public bool IsComplete { get; set; }
}

此属性的状态更改 UI 行为并更改基础 JSON 架构:

"schemas": {
    "TodoItem": {
        "required": [
            "name"
        ],
        "type": "object",
        "properties": {
            "id": {
                "type": "integer",
                "format": "int64"
            },
            "name": {
                "type": "string"
            },
            "isComplete": {
                "type": "boolean",
                "default": false
            }
        },
        "additionalProperties": false
    }
},

[Produces("application/json")] 属性添加到 API 控制器。 这样做的目的是声明控制器的操作支持 application/json 的响应内容类型:

[ApiController]
[Route("api/[controller]")]
[Produces("application/json")]
public class TodoController : ControllerBase
{

“媒体类型”下拉列表选此内容类型作为控制器的默认 GET 操作:

Swagger UI with default response content type

随着 Web API 中的数据注释的使用越来越多,UI 和 API 帮助页变得更具说明性和更为有用。

描述响应类型

使用 Web API 的开发人员最关心的问题是返回的内容,特别是响应类型和错误代码(如果不标准)。 在 XML 注释和数据注释中表示响应类型和错误代码。

Create 操作成功后返回 HTTP 201 状态代码。 发布的请求正文为 NULL 时,将返回 HTTP 400 状态代码。 如果 Swagger UI 中没有提供合适的文档,那么使用者会缺少对这些预期结果的了解。 在以下示例中,通过添加突出显示的行解决此问题:

/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <remarks>
/// Sample request:
///
///     POST /Todo
///     {
///        "id": 1,
///        "name": "Item #1",
///        "isComplete": true
///     }
///
/// </remarks>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public async Task<IActionResult> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    await _context.SaveChangesAsync();

    return CreatedAtAction(nameof(Get), new { id = item.Id }, item);
}

Swagger UI 现在清楚地记录预期的 HTTP 响应代码:

Swagger UI showing POST Response Class description 'Returns the newly created Todo item' and '400 - If the item is null' for status code and reason under Response Messages.

约定可以用作使用 [ProducesResponseType] 显式修饰各操作的替代方法。 有关详细信息,请参阅使用 Web API 约定

为了支持 [ProducesResponseType] 修饰,Swashbuckle.AspNetCore.Annotations 包提供了用于启用和丰富响应、架构和参数元数据的扩展。

自定义 UI

默认 UI 既实用又可呈现。 但是,API 文档页应代表品牌或主题。 将 Swashbuckle 组件标记为需要添加资源以提供静态文件,并构建文件夹结构以托管这些文件。

启用静态文件中间件:

app.UseHttpsRedirection();
app.UseStaticFiles();
app.MapControllers();

若要插入其他 CSS 样式表,请将其添加到项目的 wwwroot 文件夹中,并在中间件选项中指定相对路径:

app.UseSwaggerUI(options =>
{
    options.InjectStylesheet("/swagger-ui/custom.css");
});

其他资源

查看或下载示例代码如何下载

Swashbuckle 有三个主要组成部分:

  • Swashbuckle.AspNetCore.Swagger:将 SwaggerDocument 对象公开为 JSON 终结点的 Swagger 对象模型和中间件。

  • Swashbuckle.AspNetCore.SwaggerGen:从路由、控制器和模型直接生成 SwaggerDocument 对象的 Swagger 生成器。 它通常与 Swagger 终结点中间件结合,以自动公开 Swagger JSON。

  • Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的嵌入式版本。 它解释 Swagger JSON 以构建描述 Web API 功能的可自定义的丰富体验。 它包括针对公共方法的内置测试工具。

包安装

可以使用以下方法来添加 Swashbuckle:

  • 从“程序包管理器控制台”窗口:

    • 转到“视图”>“其他窗口”>“程序包管理器控制台”

    • 导航到包含 TodoApi.csproj 文件的目录

    • 请执行以下命令:

      Install-Package Swashbuckle.AspNetCore -Version 5.6.3
      
  • 从“管理 NuGet 程序包”对话框中:

    • 右键单击“解决方案资源管理器”>“管理 NuGet 包”中的项目
    • 将“包源”设置为“nuget.org”
    • 确保启用“包括预发行版”选项
    • 在搜索框中输入“Swashbuckle.AspNetCore”
    • 从“浏览”选项卡中选择最新的“Swashbuckle.AspNetCore”包,然后单击“安装”

添加并配置 Swagger 中间件

将 Swagger 生成器添加到 Startup.ConfigureServices 方法中的服务集合中:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddControllers();

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen();
}

Startup.Configure 方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务:

public void Configure(IApplicationBuilder app)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.)
    app.UseSwaggerUI();

    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

注意

Swashbuckle 依赖于 MVC 的 Microsoft.AspNetCore.Mvc.ApiExplorer 来发现路由和终结点。 如果项目调用 AddMvc,则自动发现路由和终结点。 调用 AddMvcCore 时,必须显式调用 AddApiExplorer 方法。 有关详细信息,请参阅 Swashbuckle、ApiExplorer 和路由

前述的 UseSwaggerUI 方法调用会启用 Swagger UI 工具的嵌入版本。 这取决于静态文件中间件。 如果以 .NET Framework 或 .NET Core 1.x 为目标,请将 Microsoft.AspNetCore.StaticFiles NuGet 包添加到项目。

启动应用,并导航到 http://localhost:<port>/swagger/v1/swagger.json。 生成的描述终结点的文档显示在 OpenAPI 规范 (openapi.json) 中。

可在 http://localhost:<port>/swagger 找到 Swagger UI。 通过 Swagger UI 浏览 API,并将其合并其他计划中。

提示

要在应用的根 (http://localhost:<port>/) 处提供 Swagger UI,请将 RoutePrefix 属性设置为空字符串:

app.UseSwaggerUI(c =>
{
    c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    c.RoutePrefix = string.Empty;
});

如果使用目录及 IIS 或反向代理,请使用 ./ 前缀将 Swagger 终结点设置为相对路径。 例如 ./swagger/v1/swagger.json。 使用 /swagger/v1/swagger.json 指示应用在 URL 的真实根目录中查找 JSON 文件(如果使用,加上路由前缀)。 例如,请使用 http://localhost:<port>/<route_prefix>/swagger/v1/swagger.json 而不是 http://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json

注意

默认情况下,Swashbuckle 会在 3.0 版规范(官方称为 OpenAPI 规范)中生成并公开 Swagger JSON。 为了支持向后兼容性,可以改为选择以 2.0 格式公开 JSON。 对于当前支持 OpenAPI 版本 2.0 的 Microsoft Power Apps 和 Microsoft Flow 等集成,此 2.0 格式非常重要。 若要选择采用 2.0 格式,请在 Startup.Configure 中设置 SerializeAsV2 属性:

public void Configure(IApplicationBuilder app)
{
    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger(c =>
    {
        c.SerializeAsV2 = true;
    });

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

自定义和扩展

Swagger 提供了为对象模型进行归档和自定义 UI 以匹配你的主题的选项。

Startup 类中,添加以下命名空间:

using System;
using System.Reflection;
using System.IO;

API 信息和说明

传递给 AddSwaggerGen 方法的配置操作会添加诸如作者、许可证和说明的信息:

Startup 类中,导入以下命名空间来使用 OpenApiInfo 类:

using Microsoft.OpenApi.Models;

使用 OpenApiInfo 类修改 UI 中显示的信息:

// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo
    {
        Version = "v1",
        Title = "ToDo API",
        Description = "A simple example ASP.NET Core Web API",
        TermsOfService = new Uri("https://example.com/terms"),
        Contact = new OpenApiContact
        {
            Name = "Shayne Boyer",
            Email = string.Empty,
            Url = new Uri("https://twitter.com/spboyer"),
        },
        License = new OpenApiLicense
        {
            Name = "Use under LICX",
            Url = new Uri("https://example.com/license"),
        }
    });
});

Swagger UI 显示版本的信息:

Swagger UI with version information: description, author, and see more link.

XML 注释

可使用以下方法启用 XML 注释:

  • 在解决方案资源管理器中右键单击该项目,然后选择“Edit <project_name>.csproj”。
  • 手动将突出显示的行添加到 .csproj 文件:
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

启用 XML 注释,为未记录的公共类型和成员提供调试信息。 警告消息指示未记录的类型和成员。 例如,以下消息指示违反警告代码 1591:

warning CS1591: Missing XML comment for publicly visible type or member 'TodoController.GetAll()'

要在项目范围内取消警告,请定义要在项目文件中忽略的以分号分隔的警告代码列表。 将警告代码追加到 $(NoWarn); 也会应用 C# 默认值

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

要仅针对特定成员取消警告,请将代码附入 #pragma warning 预处理程序指令中。 此方法对于不应通过 API 文档公开的代码非常有用。在以下示例中,将忽略整个 Program 类的警告代码 CS1591。 在类定义结束时还原警告代码的强制执行。 使用逗号分隔的列表指定多个警告代码。

namespace TodoApi
{
#pragma warning disable CS1591
    public class Program
    {
        public static void Main(string[] args) =>
            BuildWebHost(args).Run();

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }
#pragma warning restore CS1591
}

将 Swagger 配置为使用按照上述说明生成的 XML 文件。 对于 Linux 或非 Windows 操作系统,文件名和路径区分大小写。 例如,TodoApi.XML 文件在 Windows 上有效,但在 CentOS 上无效。

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddControllers();

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new OpenApiInfo
        {
            Version = "v1",
            Title = "ToDo API",
            Description = "A simple example ASP.NET Core Web API",
            TermsOfService = new Uri("https://example.com/terms"),
            Contact = new OpenApiContact
            {
                Name = "Shayne Boyer",
                Email = string.Empty,
                Url = new Uri("https://twitter.com/spboyer"),
            },
            License = new OpenApiLicense
            {
                Name = "Use under LICX",
                Url = new Uri("https://example.com/license"),
            }
        });

        // Set the comments path for the Swagger JSON and UI.
        var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
        var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
        c.IncludeXmlComments(xmlPath);
    });
}

在上述代码中,反射用于生成与 Web API 项目相匹配的 XML 文件名。 AppContext.BaseDirectory属性用于构造 XML 文件的路径。 一些 Swagger 功能(例如,输入参数的架构,或各自属性中的 HTTP 方法和响应代码)无需使用 XML 文档文件即可起作用。 对于大多数功能(即方法摘要以及参数说明和响应代码说明),必须使用 XML 文件。

通过向节标题添加说明,将三斜杠注释添加到操作增强了 Swagger UI。 执行 Delete 操作前添加 <summary> 元素:

/// <summary>
/// Deletes a specific TodoItem.
/// </summary>
/// <param name="id"></param>        
[HttpDelete("{id}")]
public IActionResult Delete(long id)
{
    var todo = _context.TodoItems.Find(id);

    if (todo == null)
    {
        return NotFound();
    }

    _context.TodoItems.Remove(todo);
    _context.SaveChanges();

    return NoContent();
}

Swagger UI 显示上述代码的 <summary> 元素的内部文本:

Swagger UI showing XML comment 'Deletes a specific TodoItem.' for the DELETE method.

生成的 JSON 架构驱动 UI:

"delete": {
    "tags": [
        "Todo"
    ],
    "summary": "Deletes a specific TodoItem.",
    "operationId": "ApiTodoByIdDelete",
    "consumes": [],
    "produces": [],
    "parameters": [
        {
            "name": "id",
            "in": "path",
            "description": "",
            "required": true,
            "type": "integer",
            "format": "int64"
        }
    ],
    "responses": {
        "200": {
            "description": "Success"
        }
    }
}

<remarks> 元素添加到 Create 操作方法文档。 它可以补充 <summary> 元素中指定的信息,并提供更可靠的 Swagger UI。 <remarks> 元素内容可包含文本、JSON 或 XML。

/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Sample request:
///
///     POST /Todo
///     {
///        "id": 1,
///        "name": "Item1",
///        "isComplete": true
///     }
///
/// </remarks>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>            
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}

请注意带这些附加注释的 UI 增强功能:

Swagger UI with additional comments shown.

数据注释

使用 System.ComponentModel.DataAnnotations 命名空间中找到的属性来标记模型,以帮助驱动 Swagger UI 组件。

[Required] 属性添加到 TodoItem 类的 Name 属性:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace TodoApi.Models
{
    public class TodoItem
    {
        public long Id { get; set; }

        [Required]
        public string Name { get; set; }

        [DefaultValue(false)]
        public bool IsComplete { get; set; }
    }
}

此属性的状态更改 UI 行为并更改基础 JSON 架构:

"definitions": {
    "TodoItem": {
        "required": [
            "name"
        ],
        "type": "object",
        "properties": {
            "id": {
                "format": "int64",
                "type": "integer"
            },
            "name": {
                "type": "string"
            },
            "isComplete": {
                "default": false,
                "type": "boolean"
            }
        }
    }
},

[Produces("application/json")] 属性添加到 API 控制器。 这样做的目的是声明控制器的操作支持 application/json 的响应内容类型:

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
    private readonly TodoContext _context;

“响应内容类型”下拉列表选此内容类型作为控制器的默认 GET 操作:

Swagger UI with default response content type.

随着 Web API 中的数据注释的使用越来越多,UI 和 API 帮助页变得更具说明性和更为有用。

描述响应类型

使用 Web API 的开发人员最关心的问题是返回的内容,特别是响应类型和错误代码(如果不标准)。 在 XML 注释和数据注释中表示响应类型和错误代码。

Create 操作成功后返回 HTTP 201 状态代码。 发布的请求正文为 NULL 时,将返回 HTTP 400 状态代码。 如果 Swagger UI 中没有提供合适的文档,那么使用者会缺少对这些预期结果的了解。 在以下示例中,通过添加突出显示的行解决此问题:

/// <summary>
/// Creates a TodoItem.
/// </summary>
/// <remarks>
/// Sample request:
///
///     POST /Todo
///     {
///        "id": 1,
///        "name": "Item1",
///        "isComplete": true
///     }
///
/// </remarks>
/// <param name="item"></param>
/// <returns>A newly created TodoItem</returns>
/// <response code="201">Returns the newly created item</response>
/// <response code="400">If the item is null</response>            
[HttpPost]
[ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}

Swagger UI 现在清楚地记录预期的 HTTP 响应代码:

Swagger UI showing POST Response Class description 'Returns the newly created Todo item' and '400 - If the item is null' for status code and reason under Response Messages.

在 ASP.NET Core 2.2 或更高版本中,约定可以用作使用 [ProducesResponseType] 显式修饰各操作的替代方法。 有关详细信息,请参阅使用 Web API 约定

为了支持 [ProducesResponseType] 修饰,Swashbuckle.AspNetCore.Annotations 包提供了用于启用和丰富响应、架构和参数元数据的扩展。

自定义 UI

默认 UI 既实用又可呈现。 但是,API 文档页应代表品牌或主题。 将 Swashbuckle 组件标记为需要添加资源以提供静态文件,并构建文件夹结构以托管这些文件。

如果以 .NET Framework 或 .NET Core 1.x 为目标,请将 Microsoft.AspNetCore.StaticFiles NuGet 包添加到项目:

<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.0.0" />

如果以 .NET Core 2.x 为目标并使用元包,则已安装上述 NuGet 包。

启用静态文件中间件:

public void Configure(IApplicationBuilder app)
{
    app.UseStaticFiles();

    // Enable middleware to serve generated Swagger as a JSON endpoint.
    app.UseSwagger();

    // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    app.UseRouting();
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

若要插入其他 CSS 样式表,请将其添加到项目的 wwwroot 文件夹中,并在中间件选项中指定相对路径:

app.UseSwaggerUI(c =>
{
     c.InjectStylesheet("/swagger-ui/custom.css");
}

其他资源