新彩天欢迎您!
幻海优品

ASP.NET Core Swashbuckle的使用自定义UI及扩展配置示例

1、配置添加命名空间

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

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

2、API信息和说明

传递给该AddSwaggerGen方法的配置操作会添加诸如作者,许可证和描述之类的信息:

// 注册Swagger生成器,定义一个或多个Swagger文档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显示版本信息:

httpsfileaionlifexyzsourcedownloadid5e7df699dc72d90263e632bf

3、配置XML注释

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

1) 在解决方案资源管理器中右键单击该项目,然后选择Edit <project_name>.csproj

2) 手动将显示的行添加到.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></PropertyGroup>

要仅禁止针对特定成员的警告,请将代码括在#pragma警告预处理器指令中。这种方法对于不应通过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);    });}

在前面的代码中,Reflection用于构建与Web API项目匹配的XML文件名。该AppContext.BaseDirectory属性用于构建XML文件的路径。某些Swagger功能(例如,输入参数的模式或HTTP方法以及来自相应属性的响应代码)无需使用XML文档文件即可工作。对于大多数功能,即方法摘要以及参数和响应代码的描述,必须使用XML文件。

向动作添加三斜杠注释可以通过将描述添加到节标题来增强Swagger UI。在操作上方添加<summary>元素Delete

/// <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>元素的内部文本:

httpsfileaionlifexyzsourcedownloadid5e7dfacedc72d90263e632c0

UI由生成的JSON模式驱动:

"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>元素的内容可以包括文本,JSONXML:

/// <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增强还有以下附加注释:

httpsfileaionlifexyzsourcedownloadid5e7dfaefdc72d90263e632c1

4、标签字段注解

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

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

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操作:

httpsfileaionlifexyzsourcedownloadid5e7dfb09dc72d90263e632c2

随着Web API中数据注释的使用增加,UI和API帮助页面变得更具描述性和实用性。

5、描述API响应类型

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

该Create行动在成功时返回一个HTTP 201状态码。当发布的请求正文为null时,返回HTTP 400状态代码。如果在Swagger用户界面中没有适当的文档,则消费者缺乏对这些预期结果的了解。通过在以下示例中添加突出显示的行来解决该问题:

/// <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响应代码:

httpsfileaionlifexyzsourcedownloadid5e7dfb25dc72d90263e632c3

ASP.NET Core 2.2或更高版本中,可以使用约定代替使用显式装饰单个动作[ProducesResponseType]。有关更多信息,请参阅使用Web API约定

6、自定义Swashbuckle的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并使用metapackage,则已经安装了前面的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();    });}

Swagger UI GitHub存储库获取dist文件夹的内容。该文件夹包含Swagger UI页面的必要资产。

创建一个wwwroot/swagger/ui文件夹,并将dist文件夹的内容复制到其中。

使用以下CSS 在wwwroot/swagger/ui中创建一个custom.css文件,以自定义页面标题:

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

在任何其他CSS文件之后,在ui文件夹内的index.html文件中引用custom.css

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

浏览至的index.html页面http://localhost:/swagger/ui/index.html在标题的文本框中输入https://localhost:/swagger/v1/swagger.json,然后单击"Explore"按钮。结果页面如下所示:

httpsfileaionlifexyzsourcedownloadid5e7dfb3edc72d90263e632c4

相关文档:

ASP.NET Core Web API Swagger/OpenAPI Swashbuckle.AspNetCore NSwag介绍

getting-started-with-swashbuckle

ASP.NET Core Swashbuckle的使用配置及示例

免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除