Swashbuckle 和 ASP.NET Core 入门Get started with Swashbuckle and ASP.NET Core

作者:Shayne BoyerScott AddieBy Shayne Boyer and Scott Addie

查看或下载示例代码如何下载View or download sample code (how to download)

Swashbuckle 有三个主要组成部分:There are three main components to Swashbuckle:

  • Swashbuckle.AspNetCore.Swagger:将 SwaggerDocument 对象公开为 JSON 终结点的 Swagger 对象模型和中间件。Swashbuckle.AspNetCore.Swagger: a Swagger object model and middleware to expose SwaggerDocument objects as JSON endpoints.

  • Swashbuckle.AspNetCore.SwaggerGen:从路由、控制器和模型直接生成 SwaggerDocument 对象的 Swagger 生成器。Swashbuckle.AspNetCore.SwaggerGen: a Swagger generator that builds SwaggerDocument objects directly from your routes, controllers, and models. 它通常与 Swagger 终结点中间件结合,以自动公开 Swagger JSON。It's typically combined with the Swagger endpoint middleware to automatically expose Swagger JSON.

  • Swashbuckle.AspNetCore.SwaggerUI:Swagger UI 工具的嵌入式版本。Swashbuckle.AspNetCore.SwaggerUI: an embedded version of the Swagger UI tool. 它解释 Swagger JSON 以构建描述 Web API 功能的可自定义的丰富体验。It interprets Swagger JSON to build a rich, customizable experience for describing the web API functionality. 它包括针对公共方法的内置测试工具。It includes built-in test harnesses for the public methods.

包安装Package installation

可以使用以下方法来添加 Swashbuckle:Swashbuckle can be added with the following approaches:

  • 从“程序包管理器控制台”窗口:From the Package Manager Console window:

    • 转到“视图” > “其他窗口” > “程序包管理器控制台”Go to View > Other Windows > Package Manager Console

    • 导航到包含 TodoApi.csproj 文件的目录Navigate to the directory in which the TodoApi.csproj file exists

    • 请执行以下命令:Execute the following command:

      Install-Package Swashbuckle.AspNetCore
      
  • 从“管理 NuGet 程序包”对话框中:From the Manage NuGet Packages dialog:

    • 右键单击“解决方案资源管理器” > “管理 NuGet 包”中的项目Right-click the project in Solution Explorer > Manage NuGet Packages
    • 将“包源”设置为“nuget.org”Set the Package source to "nuget.org"
    • 在搜索框中输入“Swashbuckle.AspNetCore”Enter "Swashbuckle.AspNetCore" in the search box
    • 从“浏览”选项卡中选择“Swashbuckle.AspNetCore”包,然后单击“安装”Select the "Swashbuckle.AspNetCore" package from the Browse tab and click Install

添加并配置 Swagger 中间件Add and configure Swagger middleware

导入以下命名空间以使用 Info 类:Import the following namespace to use the Info class:

using Swashbuckle.AspNetCore.Swagger;

将 Swagger 生成器添加到 Startup.ConfigureServices 方法中的服务集合中:Add the Swagger generator to the services collection in the Startup.ConfigureServices method:

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

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });
    });
}

Startup.Configure 方法中,启用中间件为生成的 JSON 文档和 Swagger UI 提供服务:In the Startup.Configure method, enable the middleware for serving the generated JSON document and the 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.), 
    // specifying the Swagger JSON endpoint.
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
    });

    app.UseMvc();
}

前面的 UseSwaggerUI 方法调用启用了静态文件中间件The preceding UseSwaggerUI method call enables the Static File Middleware. 如果以 .NET Framework 或 .NET Core 1.x 为目标,请将 Microsoft.AspNetCore.StaticFiles NuGet 包添加到项目。If targeting .NET Framework or .NET Core 1.x, add the Microsoft.AspNetCore.StaticFiles NuGet package to the project.

启动应用,并导航到 http://localhost:<port>/swagger/v1/swagger.jsonLaunch the app, and navigate to http://localhost:<port>/swagger/v1/swagger.json. 生成的描述终结点的文档显示在 Swagger 规范 (swagger.json) 中。The generated document describing the endpoints appears as shown in Swagger specification (swagger.json).

可在 http://localhost:<port>/swagger 找到 Swagger UI。The Swagger UI can be found at http://localhost:<port>/swagger. 通过 Swagger UI 浏览 API,并将其合并其他计划中。Explore the API via Swagger UI and incorporate it in other programs.

提示

要在应用的根 (http://localhost:<port>/) 处提供 Swagger UI,请将 RoutePrefix 属性设置为空字符串:To serve the Swagger UI at the app's root (http://localhost:<port>/), set the RoutePrefix property to an empty string:

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

如果使用目录及 IIS 或反向代理,请使用 ./ 前缀将 Swagger 终结点设置为相对路径。If using directories with IIS or a reverse proxy, set the Swagger endpoint to a relative path using the ./ prefix. 例如 ./swagger/v1/swagger.jsonFor example, ./swagger/v1/swagger.json. 使用 /swagger/v1/swagger.json 指示应用在 URL 的真实根目录中查找 JSON 文件(如果使用,加上路由前缀)。Using /swagger/v1/swagger.json instructs the app to look for the JSON file at the true root of the URL (plus the route prefix, if used). 例如,请使用 http://localhost:<port>/<route_prefix>/swagger/v1/swagger.json 而不是 http://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.jsonFor example, use http://localhost:<port>/<route_prefix>/swagger/v1/swagger.json instead of http://localhost:<port>/<virtual_directory>/<route_prefix>/swagger/v1/swagger.json.

自定义和扩展Customize and extend

Swagger 提供了为对象模型进行归档和自定义 UI 以匹配你的主题的选项。Swagger provides options for documenting the object model and customizing the UI to match your theme.

API 信息和说明API info and description

传递给 AddSwaggerGen 方法的配置操作会添加诸如作者、许可证和说明的信息:The configuration action passed to the AddSwaggerGen method adds information such as the author, license, and description:

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

Swagger UI 显示版本的信息:The Swagger UI displays the version's information:

包含版本信息的 Swagger UI:说明、作者以及查看更多链接

XML 注释XML comments

可使用以下方法启用 XML 注释:XML comments can be enabled with the following approaches:

  • 在“解决方案资源管理器”中右键单击该项目,然后选择“编辑 <project_name>.csproj”。Right-click the project in Solution Explorer and select Edit <project_name>.csproj.
  • 手动将突出显示的行添加到 .csproj 文件:Manually add the highlighted lines to the .csproj file:
<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
  • 右键单击“解决方案资源管理器”中的项目,再选择“属性”。Right-click the project in Solution Explorer and select Properties.
  • 选中“生成”选项卡的“输出”部分下的“XML 文档文件”框。Check the XML documentation file box under the Output section of the Build tab.

启用 XML 注释,为未记录的公共类型和成员提供调试信息。Enabling XML comments provides debug information for undocumented public types and members. 警告消息指示未记录的类型和成员。Undocumented types and members are indicated by the warning message. 例如,以下消息指示违反警告代码 1591:For example, the following message indicates a violation of warning code 1591:

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

要在项目范围内取消警告,请定义要在项目文件中忽略的以分号分隔的警告代码列表。To suppress warnings project-wide, define a semicolon-delimited list of warning codes to ignore in the project file. 将警告代码追加到 $(NoWarn); 也会应用 C# 默认值Appending the warning codes to $(NoWarn); applies the C# default values too.

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>
<PropertyGroup>
  <DocumentationFile>bin\$(Configuration)\$(TargetFramework)\$(AssemblyName).xml</DocumentationFile>
  <NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>

要仅针对特定成员取消警告,请将代码附入 #pragma warning 预处理程序指令中。To suppress warnings only for specific members, enclose the code in #pragma warning preprocessor directives. 此方法对于不应通过 API 文档公开的代码非常有用。在以下示例中,将忽略整个 Program 类的警告代码 CS1591。This approach is useful for code that shouldn't be exposed via the API docs. In the following example, warning code CS1591 is ignored for the entire Program class. 在类定义结束时还原警告代码的强制执行。Enforcement of the warning code is restored at the close of the class definition. 使用逗号分隔的列表指定多个警告代码。Specify multiple warning codes with a comma-delimited list.

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 文件。Configure Swagger to use the XML file that's generated with the preceding instructions. 对于 Linux 或非 Windows 操作系统,文件名和路径区分大小写。For Linux or non-Windows operating systems, file names and paths can be case-sensitive. 例如,“TodoApi.XML”文件在 Windows 上有效,但在 CentOS 上无效。For example, a TodoApi.XML file is valid on Windows but not CentOS.

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt => 
        opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc()
        .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info
        {
            Version = "v1",
            Title = "ToDo API",
            Description = "A simple example ASP.NET Core Web API",
            TermsOfService = "None",
            Contact = new Contact
            {
                Name = "Shayne Boyer",
                Email = string.Empty,
                Url = "https://twitter.com/spboyer"
            },
            License = new License
            {
                Name = "Use under LICX",
                Url = "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);
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt => 
        opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc();

    // Register the Swagger generator, defining 1 or more Swagger documents
    services.AddSwaggerGen(c =>
    {
        c.SwaggerDoc("v1", new Info
        {
            Version = "v1",
            Title = "ToDo API",
            Description = "A simple example ASP.NET Core Web API",
            TermsOfService = "None",
            Contact = new Contact
            {
                Name = "Shayne Boyer",
                Email = string.Empty,
                Url = "https://twitter.com/spboyer"
            },
            License = new License
            {
                Name = "Use under LICX",
                Url = "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);
    });
}
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<TodoContext>(opt =>
        opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc();

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

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

在上述代码中,反射用于生成与 Web API 项目相匹配的 XML 文件名。In the preceding code, Reflection is used to build an XML file name matching that of the web API project. AppContext.BaseDirectory属性用于构造 XML 文件的路径。The AppContext.BaseDirectory property is used to construct a path to the XML file. 一些 Swagger 功能(例如,输入参数的架构,或各自属性中的 HTTP 方法和响应代码)无需使用 XML 文档文件即可起作用。Some Swagger features (for example, schemata of input parameters or HTTP methods and response codes from the respective attributes) work without the use of an XML documentation file. 对于大多数功能(即方法摘要以及参数说明和响应代码说明),必须使用 XML 文件。For most features, namely method summaries and the descriptions of parameters and response codes, the use of an XML file is mandatory.

通过向节标题添加说明,将三斜杠注释添加到操作增强了 Swagger UI。Adding triple-slash comments to an action enhances the Swagger UI by adding the description to the section header. 执行 Delete 操作前添加 <summary> 元素:Add a <summary> element above the Delete action:

/// <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> 元素的内部文本:The Swagger UI displays the inner text of the preceding code's <summary> element:

显示 DELETE 方法的 XML 注释“删除特定 TodoItem”

生成的 JSON 架构驱动 UI:The UI is driven by the generated JSON schema:

"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 操作方法文档。Add a <remarks> element to the Create action method documentation. 它可以补充 <summary> 元素中指定的信息,并提供更可靠的 Swagger UI。It supplements information specified in the <summary> element and provides a more robust Swagger UI. <remarks> 元素内容可包含文本、JSON 或 XML。The <remarks> element content can consist of text, JSON, or 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(typeof(TodoItem), 201)]
[ProducesResponseType(400)]
public IActionResult Create([FromBody] TodoItem item)
{
    if (item == null)
    {
        return BadRequest();
    }

    _context.TodoItems.Add(item);
    _context.SaveChanges();

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}
/// <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(201)]
[ProducesResponseType(400)]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

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

请注意带这些附加注释的 UI 增强功能:Notice the UI enhancements with these additional comments:

显示包含其他注释的 Swagger UI

数据注释Data annotations

使用 System.ComponentModel.DataAnnotations 命名空间中的属性来修饰模型,以帮助驱动 Swagger UI 组件。Decorate the model with attributes, found in the System.ComponentModel.DataAnnotations namespace, to help drive the Swagger UI components.

[Required] 属性添加到 TodoItem 类的 Name 属性:Add the [Required] attribute to the Name property of the TodoItem class:

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 架构:The presence of this attribute changes the UI behavior and alters the underlying JSON schema:

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

[Produces("application/json")] 属性添加到 API 控制器。Add the [Produces("application/json")] attribute to the API controller. 这样做的目的是声明控制器的操作支持 application/json 的响应内容类型:Its purpose is to declare that the controller's actions support a response content type of application/json:

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

“响应内容类型”下拉列表选此内容类型作为控制器的默认 GET 操作:The Response Content Type drop-down selects this content type as the default for the controller's GET actions:

包含默认响应内容类型的 Swagger UI

随着 Web API 中的数据注释的使用越来越多,UI 和 API 帮助页变得更具说明性和更为有用。As the usage of data annotations in the web API increases, the UI and API help pages become more descriptive and useful.

描述响应类型Describe response types

使用 Web API 的开发人员最关心的问题是返回的内容,特别是响应类型和错误代码(如果不标准)。Developers consuming a web API are most concerned with what's returned—specifically response types and error codes (if not standard). 在 XML 注释和数据注释中表示响应类型和错误代码。The response types and error codes are denoted in the XML comments and data annotations.

Create 操作成功后返回 HTTP 201 状态代码。The Create action returns an HTTP 201 status code on success. 发布的请求正文为 NULL 时,将返回 HTTP 400 状态代码。An HTTP 400 status code is returned when the posted request body is null. 如果 Swagger UI 中没有提供合适的文档,那么使用者会缺少对这些预期结果的了解。Without proper documentation in the Swagger UI, the consumer lacks knowledge of these expected outcomes. 在以下示例中,通过添加突出显示的行解决此问题:Fix that problem by adding the highlighted lines in the following example:

/// <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(typeof(TodoItem), 201)]
[ProducesResponseType(400)]
public IActionResult Create([FromBody] TodoItem item)
{
    if (item == null)
    {
        return BadRequest();
    }

    _context.TodoItems.Add(item);
    _context.SaveChanges();

    return CreatedAtRoute("GetTodo", new { id = item.Id }, item);
}
/// <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(201)]
[ProducesResponseType(400)]
public ActionResult<TodoItem> Create(TodoItem item)
{
    _context.TodoItems.Add(item);
    _context.SaveChanges();

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

Swagger UI 现在清楚地记录预期的 HTTP 响应代码:The Swagger UI now clearly documents the expected HTTP response codes:

Swagger UI 针对“响应消息”下的状态代码和原因显示 POST 响应类描述“返回新建的待办事项”和“400 - 如果该项为 null”

在 ASP.NET Core 2.2 或更高版本中,约定可以用作使用 [ProducesResponseType] 显式修饰各操作的替代方法。In ASP.NET Core 2.2 or later, conventions can be used as an alternative to explicitly decorating individual actions with [ProducesResponseType]. 有关更多信息,请参见使用 Web API 约定For more information, see 使用 Web API 约定.

自定义 UICustomize the UI

股票 UI 既实用又可呈现。The stock UI is both functional and presentable. 但是,API 文档页应代表品牌或主题。However, API documentation pages should represent your brand or theme. 将 Swashbuckle 组件标记为需要添加资源以提供静态文件,并构建文件夹结构以托管这些文件。Branding the Swashbuckle components requires adding the resources to serve static files and building the folder structure to host those files.

如果以 .NET Framework 或 .NET Core 1.x 为目标,请将 Microsoft.AspNetCore.StaticFiles NuGet 包添加到项目:If targeting .NET Framework or .NET Core 1.x, add the Microsoft.AspNetCore.StaticFiles NuGet package to the project:

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

如果以 .NET Core 2.x 为目标并使用元包,则已安装上述 NuGet 包。The preceding NuGet package is already installed if targeting .NET Core 2.x and using the metapackage.

启用静态文件中间件:Enable Static File Middleware:

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.UseMvc();
}

Swagger UI GitHub 存储库中获取 dist 文件夹的内容。Acquire the contents of the dist folder from the Swagger UI GitHub repository. 此文件夹包含 Swagger UI 页必需的资产。This folder contains the necessary assets for the Swagger UI page.

创建 wwwroot/swagger/ui 文件夹,然后将 dist 文件夹的内容复制到其中。Create a wwwroot/swagger/ui folder, and copy into it the contents of the dist folder.

使用以下 CSS 在 wwwroot/swagger/ui 中创建 custom.css 文件,以自定义页面标题:Create a custom.css file, in wwwroot/swagger/ui, with the following CSS to customize the page header:

.swagger-ui .topbar {
    background-color: #000;
    border-bottom: 3px solid #547f00;
}

引用其他 CSS 文件后,引用 index.html 文件中的“custom.css”:Reference custom.css in the index.html file, after any other CSS files:

<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+Web:400,600,700" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="./swagger-ui.css">
<link rel="stylesheet" type="text/css" href="custom.css">

浏览到 http://localhost:<port>/swagger/ui/index.html 中的 index.html 页。Browse to the index.html page at http://localhost:<port>/swagger/ui/index.html. 在标题文本框中输入 http://localhost:<port>/swagger/v1/swagger.json,然后单击“浏览”按钮。Enter http://localhost:<port>/swagger/v1/swagger.json in the header's textbox, and click the Explore button. 生成的页面如下所示:The resulting page looks as follows:

使用自定义标题的 Swagger UI

还可以对页面执行更多操作。There's much more you can do with the page. Swagger UI GitHub 存储库中查看 UI 资源的完整功能。See the full capabilities for the UI resources at the Swagger UI GitHub repository.