asp.net core使用Swashbuckle.AspNetCore(swagger)生成接口文檔

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

Swashbuckle.AspNetCore:swagger的asp.net core實現
項目地址:https://github.com/domaindrivendev/Swashbuckle.AspNetCore
仔細看了下readme,發如今百度找半天的東西其實readme裏面就有...git

開局一張圖,而後開始編,一些基本的asp.net core東西就再也不贅述,本文只對Swashbuckle.AspNetCore的幾個使用要點進行描述。github

圖片

如上圖所示,包含功能以下(完整示例見文末)

  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>bin\Debug\netcoreapp2.0\項目名稱.xml</DocumentationFile>
      </PropertyGroup>
複製代碼
  1. 使用Swagger並注入漢化腳本

c.SwaggerDoc配置接口描述信息
c.OperationFilter可經過IOperationFilter接口去添加一些公共的參數
c.DocumentFilter經過IDocumentFilter接口去生成控制器的標籤(描述)
注:ConfigureServices的方法返回值修改了,爲了可以正常的使用ServiceLocator獲取服務web

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問題。json

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();
}
複製代碼

實現 IDocumentFilterIOperationFilter

經過IOperationFilter接口能夠添加一些公共的參數,添加參數到header或者上傳圖片等
經過IDocumentFilter接口能夠生成控制器的標籤(描述)
調用方式分別爲:
c.OperationFilter<AssignOperationVendorExtensions>();
c.DocumentFilter<ApplyTagDescriptions>();api

//添加標籤
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文檔了~
注:bash

  1. action方法或者控制器(或者繼承的)必須有一個包含[Route]特性標記
  2. action方法必須添加請求類型[HttpGet]/[HttpPost]/..

如何自動將token保存並賦值

使用js生成了文本框到.authorize-wrapper,將值保存到了本地存儲中,而後會根據接口版本將版本號參數進行復制app

$(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='width: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)]便可asp.net

文章完整示例

Demo下載
Demo倉庫地址dom

相關文章
相關標籤/搜索