zoukankan      html  css  js  c++  java
  • asp.net core使用Swashbuckle.AspNetCore(swagger)生成接口文档

    asp.net core中使用Swashbuckle.AspNetCore生成接口文档

    Swashbuckle.AspNetCore:swagger的asp.net core实现,本文使用版本为v1.1.0
    项目地址:https://github.com/domaindrivendev/Swashbuckle.AspNetCore
    仔细看了下readme,发现在百度找半天的东西其实readme里面就有...

    开局一张图,然后开始编,一些基本的asp.net core东西就不再赘述,本文只对Swashbuckle.AspNetCore的几个使用要点进行描述。

    图片
    如上图所示,包含功能如下(完整示例见文末)

    1. 基础使用,添加controler的说明(IDocumentFilter)
    2. 汉化操作按钮
    3. 添加通用参数(header)-实现IOperationFilter
    4. 多版本控制(暂时见demo)
    5. 使用JWT的简单接口验证(暂时见demo)

    构建一个webapi项目并使用swagger

    1. 新建asp.net core webapi项目 dotnet new webapi
    2. 安装nuget包:Swashbuckle.AspNetCore,本文使用版本1.1.0,.net core版本2.0+
    3. 编辑解决方案添加(或者在vs中项目属性->生成->勾选生成xml文档文件)如下配置片段
          <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
            <DocumentationFile>binDebug
    etcoreapp2.0项目名称.xml</DocumentationFile>
          </PropertyGroup>
    1. 使用Swagger并注入汉化脚本

    c.SwaggerDoc配置接口描述信息
    c.OperationFilter可通过IOperationFilter接口去添加一些公共的参数
    c.DocumentFilter通过IDocumentFilter接口去生成控制器的标签(描述)
    注:ConfigureServices的方法返回值修改了,为了能够正常的使用ServiceLocator获取服务

    private const string _Project_Name = "AspNetCoreSwaggerDemo";//nameof(AspNetCoreSwaggerDemo);
    public IServiceProvider ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddSingleton(new ApiTokenConfig("A3FFB16D-D2C0-4F25-BACE-1B9E5AB614A6"));
        services.AddScoped<IApiTokenService, ApiTokenService>();
        services.AddSwaggerGen(c =>
        {
            typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
            {
                c.SwaggerDoc(version, new Swashbuckle.AspNetCore.Swagger.Info
                 {
                     Version = version,
                     Title = $"{_Project_Name} 接口文档",
                     Description = $"{_Project_Name} HTTP API " + version,
                     TermsOfService = "None"
                 });
            });
            var basePath = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default.Application.ApplicationBasePath;
            var xmlPath = System.IO.Path.Combine(basePath, $"{_Project_Name}.xml");
            c.IncludeXmlComments(xmlPath);
            //添加自定义参数,可通过一些特性标记去判断是否添加
            c.OperationFilter<AssignOperationVendorExtensions>();
            //添加对控制器的标签(描述)
            c.DocumentFilter<ApplyTagDescriptions>();
        });
    
        services.AddMvc();
        return services.BuildServiceProvider();
    }

    使用InjectOnCompleteJavaScript注入汉化js脚本即可
    注:我在这个汉化脚本中添加了保存和读取赋值token/版本的js代码
    ApiVersions为枚举,配置api版本,以期通过CustomRoute特性标记解决历史api问题。

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            //ApiVersions为自定义的版本枚举
            typeof(ApiVersions)
            .GetEnumNames()
            .OrderByDescending(e => e)
            .ToList()
            .ForEach(version =>
            {
                //版本控制
                c.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"{_Project_Name} {version}");
             });
             //注入汉化脚本
             c.InjectOnCompleteJavaScript($"/swagger_translator.js");
        });
        //通过ServiceLocator.Resolve<Service接口>()获取注入的服务
        ServiceLocator.Configure(app.ApplicationServices);
        app.UseStaticFiles();
        app.UseMvc();
    }

    实现 IDocumentFilter 及 IOperationFilter

    通过IOperationFilter接口可以添加一些公共的参数,添加参数到header或者上传图片等
    通过IDocumentFilter接口可以生成控制器的标签(描述)
    调用方式分别为:
    c.OperationFilter<AssignOperationVendorExtensions>();
    c.DocumentFilter<ApplyTagDescriptions>();

    //添加标签
    public class ApplyTagDescriptions : IDocumentFilter
    {
        public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.Tags = new List<Tag>
            {
                //添加对应的控制器描述 这个是好不容易在issues里面翻到的
                new Tag { Name = "Account", Description = "登录相关接口" },
                new Tag { Name = "UserCenter", Description = "用户中心接}
            };
        }
    }
    //添加通用参数,若in='header'则添加到header中,默认query参数
    public class AssignOperationVendorExtensions : IOperationFilter
    {
        public void Apply(Operation operation, OperationFilterContext context)
        {
            operation.Parameters = operation.Parameters ?? new List<IParameter>();
            //MemberAuthorizeAttribute 自定义的身份验证特性标记
            var isAuthor = operation != null && context != null && context.ApiDescription.ControllerAttributes().Any(e => e.GetType() == typeof(MemberAuthorizeAttribute)) || context.ApiDescription.ActionAttributes().Any(e => e.GetType() == typeof(MemberAuthorizeAttribute));
            if (isAuthor)
            {
                //in query header 
                operation.Parameters.Add(new NonBodyParameter() { 
                        Name = "x-token", 
                        In = "header", //query formData ..
                        Description = "身份验证票据", 
                        Required = false, 
                        Type = "string" 
               });
            }
        }
    }

    配置完成后,给Controler,Action添加上注释和请求类型就可以访问/swagger查看你的api文档了~
    注:

    1. action方法或者控制器(或者继承的)必须有一个包含[Route]特性标记
    2. action方法必须添加请求类型[HttpGet]/[HttpPost]/..

    如何自动将token保存并赋值

    使用js生成了文本框到.authorize-wrapper,将值保存到了本地存储中,然后会根据接口版本将版本号参数进行复制

    $(function () {
        //汉化
        window.SwaggerTranslator.translate();
        /***************下面是添加的token相关代码*******************/
        window.saveToken=function() {
            var test_token = $("#customtoken").val();
            localStorage.setItem("test_x_token", $("#customtoken").val());
            $("input[name='X-Token']").val(test_token)
        }
        //token保存
        var test_token = localStorage.getItem("test_x_token")||"";
        $(".authorize-wrapper").append("X-Token:<input type='text' id='customtoken' value='" + test_token +"' style='50%' /> <button onClick='saveToken()'>保存</button>")
        $("input[name='X-Token']").val(test_token)
        $("input[name='X-Version']").val(swaggerUi.api.info.version)
    
    });

    如何忽略一个接口

    为Controller或者Action方法上添加特性标记[ApiExplorerSettings(IgnoreApi =true)]即可

    下一篇:Swashbuckle.AspNetCore3.0的二次封装与使用

    文章完整示例

    Demo下载
    Demo仓库地址

    注:Demo 未修改默认启动路径,故应使用 /swagger/ 访问文档:,也可自行修改 /Properties/launchSettings.json 配置默认路径

    作者:易墨 
    个人小站:http://www.yimo.link 
    纯静态工具站点:http://tools.yimo.link/ 
    说明:欢迎拍砖,不足之处还望园友们指出; 
    迷茫大概是因为想的太多做的太少。

     
    分类: .net core
  • 相关阅读:
    Oracle基础 (十二)数学函数
    Oracle基础 (十一)字符串函数
    Oracle基础(十) DML数据操作
    Oracle 常用命令大全
    Oracle 常用的SQL语法和数据对象
    Server.MapPath()
    登陆sharepoint的主页,提示:文件存在(异常来自 HRESULT:0x80070050)
    如何查看电脑的开机时间
    SQL 2008登录的域账户与数据库服务器不再同一个域的 处理方法
    发布MVC项目到服务器上时候遇到的 模块 DirectoryListingModule 通知 ExecuteRequestHandler 处理程序 StaticFile 错误代码 0x00000000
  • 原文地址:https://www.cnblogs.com/webenh/p/11577748.html
Copyright © 2011-2022 走看看