asp.net core using Swashbuckle.AspNetCore (swagger) generates the interface documentation

asp.net core generates the interface documentation used Swashbuckle.AspNetCore

Swashbuckle.AspNetCore: asp.net core realization of swagger, as used herein version v1.1.0
Project Address: https://github.com/domaindrivendev/Swashbuckle.AspNetCore
carefully read readme, found half a day looking for something in Baidu in fact readme inside there ...

Start a picture, and then began to compile some basic asp.net core things will not go into, this article only Swashbuckle.AspNetCorea few points of use are described.

image
As shown above, it comprises the following functions (see the end the complete sample)

  1. Basic use, add a description of the controler ( IDocumentFilter)
  2. Speaking of the operation buttons
  3. Add general parameters (header) - realizationIOperationFilter
  4. Multi-version control (temporarily see demo)
  5. JWT using simple interface verification (temporarily see demo)

Webapi build a project and use swagger

  1. New asp.net core webapi project dotnet new webapi
  2. Nuget installation package: Swashbuckle.AspNetCorepaper using version 1.1.0, .net core version 2.0+
  3. Editing solution added (or vs the Project Properties -> Build -> tick generates xml document file) follows segment
      <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
        <DocumentationFile>bin\Debug\netcoreapp2.0\项目名称.xml</DocumentationFile> </PropertyGroup>
  1. Use Swagger and injected finished script

c.SwaggerDocConfiguring interface description
c.OperationFilterby IOperationFiltergoing to add some parameters common to the interface
c.DocumentFilterthrough IDocumentFilterto a label generation controller (to be described) interface
Note: ConfigureServicesReturns the value of the modification, in order to use the normal ServiceLocatoraccess to services

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(); }

Use InjectOnCompleteJavaScriptthe injection finished js script can
Note: I added in the finished script to save and read js code assignment token / version of the
ApiVersionsenumeration, configuration api version in order by CustomRoutemarking characteristics to solve the problem api history.

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(); }

Achieve  IDocumentFilter and IOperationFilter

By IOperationFilteradd some parameters common interfaces, add parameters to the header or upload pictures
by IDocumentFiltertag may generate a controller (to be described) interface
is called, respectively:
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" }); } } }

Once configured, to Controler, Action and add comments on the type of request to access / swagger check your api documentation of ~
Note:

  1. The method or the controller action (or inheritance) must contain a [Route]characteristic marker
  2. The method of action request type must be added[HttpGet]/[HttpPost]/..

How to automatically save and assign the token

Js used to generate the text box .authorize-wrapper, the value is stored in the local storage, and will copy the version number The interface version parameter

$(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) });

How to ignore an interface

Add the characteristic methods for labeling Action Controller or [ApiExplorerSettings(IgnoreApi =true)]to

Next: secondary packaging and the use Swashbuckle.AspNetCore3.0

A complete sample article

Demo Download
Demo warehouse address

NOTE: Demo modify the default startup path, it should be used  /swagger/ to access documents: can also be modified self-  /Properties/launchSettings.json configured default path

Author: Yi ink 
individual station: http://www.yimo.link 
purely static tools site: http://tools.yimo.link/ 
Description: Welcome Paizhuan, the deficiency also pointed out Wangyuandongli faithful; 
confused about It is because too many want to do too little.

 
Category:  the .NET Core

 

asp.net core generates the interface documentation used Swashbuckle.AspNetCore

Swashbuckle.AspNetCore: asp.net core realization of swagger, as used herein version v1.1.0
Project Address: https://github.com/domaindrivendev/Swashbuckle.AspNetCore
carefully read readme, found half a day looking for something in Baidu in fact readme inside there ...

Start a picture, and then began to compile some basic asp.net core things will not go into, this article only Swashbuckle.AspNetCorea few points of use are described.

image
As shown above, it comprises the following functions (see the end the complete sample)

  1. Basic use, add a description of the controler ( IDocumentFilter)
  2. Speaking of the operation buttons
  3. Add general parameters (header) - realizationIOperationFilter
  4. Multi-version control (temporarily see demo)
  5. JWT using simple interface verification (temporarily see demo)

Webapi build a project and use swagger

  1. New asp.net core webapi project dotnet new webapi
  2. Nuget installation package: Swashbuckle.AspNetCorepaper using version 1.1.0, .net core version 2.0+
  3. Editing solution added (or vs the Project Properties -> Build -> tick generates xml document file) follows segment
      <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
        <DocumentationFile>bin\Debug\netcoreapp2.0\项目名称.xml</DocumentationFile> </PropertyGroup>
  1. Use Swagger and injected finished script

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='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)]即可

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

文章完整示例

Demo下载
Demo仓库地址

NOTE: Demo modify the default startup path, it should be used  /swagger/ to access documents: can also be modified self-  /Properties/launchSettings.json configured default path

Guess you like

Origin www.cnblogs.com/webenh/p/11577748.html