ASP.NET Core 2 学习笔记(十三)Swagger

Swagger也算是行之有年的API文件生成器,只要在API上使用C#的<summary />文件注解标签,就可以产生精美的线上文件,并且对RESTful API有良好的支持。不仅支持生成文件,还支持模拟调用的交互功能,连Postman都不用打开就能测API。
本篇将介绍如何通过Swagger产生ASP.NET Core的RESTful API文件。

安装套件

要在ASP.NET Core使用Swagger需要安装Swashbuckle.AspNetCore套件。
通过过.NET Core CLI在项目文件夹执行安装指令:

dotnet add package Swashbuckle.AspNetCore

注册Swagger

Startup.csConfigureServices加入Swagger的服务及Middleware。如下:

using Swashbuckle.AspNetCore.Swagger;
// ...
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc()
                .AddJsonOptions(options => {
                    options.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                });

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc(
                // name: 关系到 SwaggerDocument 的 URL 位置。
                name: "v1", 
                // info: 是用于 SwaggerDocument 版本信息的提示(內容非必填)。
                info: new Info
                {
                    Title = "RESTful API",
                    Version = "1.0.0",
                    Description = "This is ASP.NET Core RESTful API Sample.",
                    TermsOfService = "None",
                    Contact = new Contact { 
                        Name = "SnailDev", 
                        Url = "http://www.cnblogs.com/snaildev/" 
                    },
                    License = new License { 
                        Name = "CC BY-NC-SA 4.0", 
                        Url = "https://creativecommons.org/licenses/by-nc-sa/4.0/" 
                    }
                }
            );
        });
    }
    
    public void Configure(IApplicationBuilder app)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint(
                // url: 需配合 SwaggerDoc 的 name。 "/swagger/{SwaggerDoc name}/swagger.json"
                url: "/swagger/v1/swagger.json", 
                // name: 用于 Swagger UI 右上角选择不同版本的 SwaggerDocument 提示名称使用。
                name: "RESTful API v1.0.0"
            );
        });

        app.UseMvc();
    }
}
  • AddSwaggerGen
    Swagger生成器是负责取得API的规格并产生SwaggerDocument物件。
  • UseSwagger
    Swagger Middleware负责路由,提供SwaggerDocument物件。
    可以从URL查看Swagger产生器产生的SwaggerDocument物件。
    http://localhost:5000/swagger/v1/swagger.json
  • UseSwaggerUI
    SwaggerUI是负责将SwaggerDocument物件变成漂亮的界面。
    预设URL:http://localhost:5000/swagger

API沿用ASP.NET Core 2 学习笔记(十二)REST-Like API的示例程序。

设定完成后,启动网站就能开启Swagger UI 了。下面如下:

文件注解标签

在API加入<summary />文件注解标签。如下:

// ...
[Route("api/[controller]s")]
public class UserController : Controller
{
    /// <summary>
    /// 查询使用者清单
    /// </summary>
    /// <param name="q">查询使用者名称</param>
    /// <returns>使用者清单</returns>
    [HttpGet]
    public ResultModel Get(string q) {
        // ...
    }
} 

再次打开Swagger,会发现没有显示说明,因为没有设定.NET 的XML 文件目录,所以Swagger 抓不到说明是正常的。

打开*.csproj,在<Project />区块中插入以下代码:

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>bin\Debug\netcoreapp2.0\Api.xml</DocumentationFile>
    <NoWarn>1591</NoWarn>
  </PropertyGroup>

以我示例的*.csproj内容如下:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.0</TargetFramework>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>bin\Debug\netcoreapp2.0\Api.xml</DocumentationFile>
    <NoWarn>1591</NoWarn>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.8" />
    <PackageReference Include="Swashbuckle.AspNetCore" Version="2.5.0" />
  </ItemGroup>

</Project>

然后在Swagger生成器设定读取<DocumentationFile>指定的XML文件目录位置:

// ...
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        // ...
        services.AddSwaggerGen(c =>
        {
            // ...
            var filePath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "Api.xml");
            c.IncludeXmlComments(filePath);
        });
    }
}

返回格式

以RESTful API的例子来看,返回的格式都是JSON,所以可以直接在Controller加上[Produces("application/json")]表示返回的类型都是JSON,在Swagger的Response Content Type选项就会被锁定只有application/json可以使用。如下:

// ...
[Route("api/[controller]s")]
[Produces("application/json")]
public class UserController : Controller
{
    // ...
}

返回类型

若有预期API在不同的HTTP Status Code时,会返回不同的对象,可以透过[ProducesResponseType(type)]定义返回的对象。在Swagger中就可以清楚看到该API可能会发生的HTTP Status Code及返回对象。例如:

// ...
[Route("api/[controller]s")]
[Produces("application/json")]
public class UserController : Controller
{
    /// <summary>
    /// 查询使用者清单
    /// </summary>
    /// <param name="q">查询使用者名称</param>
    /// <returns>使用者清单</returns>
    [HttpGet]
    [ProducesResponseType(typeof(ResultModel<IEnumerable<UserModel>>), 200)]
    [ProducesResponseType(typeof(ResultModel<string>), 500)]
    public ResultModel<IEnumerable<UserModel>> Get(string q)
    {
        // ...
    }
}

执行结果

参考

ASP.NET Core Web API Help Pages using Swagger 
Swagger tools for documenting API's built on ASP.NET Core

 

老司机发车啦:https://github.com/SnailDev/SnailDev.NETCore2Learning 

posted @ 2018-06-07 14:46  snailteam  阅读(1054)  评论(0编辑  收藏  举报