在ASP.NET Core web API中使用Swagger/OpenAPI(NSwag)


简介

NSwag有以下能力:

  • SwaggerUI界面和Swagger生成器。
  • 灵活的代码生成能力

有了NSwag,你可以不需要一个已经出来的API,你可以用第三方的API来与Swagger配合并且生成一个客户端实现。NSwag可以加快你的开发周期,并且轻松适应API的改变,升级,迭代。

一.安装包(NSwag.AspNetCore

右击项目选择管理Nuget程序包

按名字搜索包,然后选择包,选择对应版本,然后安装

二.注册Swagger服务并启用中间件

Startup.ConfigureServices方法中注册需要的Swagger服务

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

    // Register the Swagger services
    services.AddSwaggerDocument();
}

Startup.Configure方法中启用生成Swagger规范文档(openapi.json)和SwaggerUI的中间件

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

    // Register the Swagger generator and the Swagger UI middlewares
    app.UseOpenApi();
    app.UseSwaggerUi3();

    app.UseMvc();
}

运行程序,通过如下地址导航到对应的

  • 通过http://localhost:/swagger查看SwaggerUI界面
  • 通过`http://localhost:/swagger/v1/swagger.json查看Swagger规范文档(openapi.json

使用NSwagStudio生成代码

下载并使用NSwagStudio,由于我没用过这个,不做详解

API信息和描述

如果您想在Swagger UI中添加一些对API的描述信息,比如作者、许可证、服务条款等信息:
Program.cs类中引入OpenApiInfo类的命名空间

using Microsoft.OpenApi.Models;

然后在Program.cs文件中的ConfigureServices方法中通过services.AddSwaggerGen方法的配置对象进行就改,模板如下:

services.AddSwaggerDocument(config =>
{
    config.PostProcess = document =>
    {
        document.Info.Version = "v1";
        document.Info.Title = "ToDo API";
        document.Info.Description = "A simple ASP.NET Core web API";
        document.Info.TermsOfService = "None";
        document.Info.Contact = new NSwag.OpenApiContact
        {
            Name = "Shayne Boyer",
            Email = string.Empty,
            Url = "https://twitter.com/spboyer"
        };
        document.Info.License = new NSwag.OpenApiLicense
        {
            Name = "Use under LICX",
            Url = "https://example.com/license"
        };
    };
});

对应SwaggerUI中

XML注释

如果您想启用XML注释以及生成对应的XML注释文档,右击的的项目文件,然后点击编辑项目文件

添加true即可启用XML注释


  
  true

开启这个功能后,如果您的程序中有没有经过XML注释的类型或者成员,您将会看到如下警告信息:

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

您觉得烦,可以在编辑项目文件中添加$(NoWarn);1591来取消这种警告


  
  $(NoWarn);1591

您也可以通过如下宏定义的方式对整段代码取消1591警告信息

namespace SwashbuckleSample.Models
{
#pragma warning disable CS1591
    public class TodoContext : DbContext
    {
        public TodoContext(DbContextOptions options) : base(options) { }

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

更多请参考: