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.AspNetCore
a few points of use are described.
As shown above, it comprises the following functions (see the end the complete sample)
- Basic use, add a description of the controler (
IDocumentFilter
) - Speaking of the operation buttons
- Add general parameters (header) - realization
IOperationFilter
- Multi-version control (temporarily see demo)
- JWT using simple interface verification (temporarily see demo)
Webapi build a project and use swagger
- New asp.net core webapi project
dotnet new webapi
- Nuget installation package:
Swashbuckle.AspNetCore
paper using version 1.1.0, .net core version 2.0+ - 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>
- Use Swagger and injected finished script
c.SwaggerDoc
Configuring interface descriptionc.OperationFilter
byIOperationFilter
going to add some parameters common to the interfacec.DocumentFilter
throughIDocumentFilter
to a label generation controller (to be described) interface
Note:ConfigureServices
Returns the value of the modification, in order to use the normalServiceLocator
access 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
InjectOnCompleteJavaScript
the injection finished js script can
Note: I added in the finished script to save and read js code assignment token / version of theApiVersions
enumeration, configuration api version in order byCustomRoute
marking 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
IOperationFilter
add some parameters common interfaces, add parameters to the header or upload pictures
byIDocumentFilter
tag 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:
- The method or the controller action (or inheritance) must contain a
[Route]
characteristic marker - 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.
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.AspNetCore
a few points of use are described.
As shown above, it comprises the following functions (see the end the complete sample)
- Basic use, add a description of the controler (
IDocumentFilter
) - Speaking of the operation buttons
- Add general parameters (header) - realization
IOperationFilter
- Multi-version control (temporarily see demo)
- JWT using simple interface verification (temporarily see demo)
Webapi build a project and use swagger
- New asp.net core webapi project
dotnet new webapi
- Nuget installation package:
Swashbuckle.AspNetCore
paper using version 1.1.0, .net core version 2.0+ - 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>
- 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文档了~
注:
- action方法或者控制器(或者继承的)必须有一个包含
[Route]
特性标记 - 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的二次封装与使用
文章完整示例
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