Swagger其实包含了三个部分,分别是Swagger Editor文档接口编辑器,根据接口文档生成code的Swagger Codegen,以及生成在线文档的Swagger UI。
在AspNetCore中一般使用Microsoft封装的Swashbuckle来使用Swagger UI,这是一个AspNetCore的中间件。和其余中间件同样都是分为register和use两个部分。json
VS中很简单,直接用NuGet安装Swashbuckle.AspNetCore便可。app
或者使用命令行: dotnet add package --version xxx Swashbuckle.AspNetCore编辑器
全部Swagger UI注册的configue相关的内容都放在AddSwaggerGen这个方法里面:ui
namespace Microsoft.Extensions.DependencyInjection { public static class SwaggerGenServiceCollectionExtensions { public static IServiceCollection AddSwaggerGen(this IServiceCollection services, Action<SwaggerGenOptions> setupAction = null); public static void ConfigureSwaggerGen(this IServiceCollection services, Action<SwaggerGenOptions> setupAction); } }
AddSwaggerGen这个方法主要用户注册中间件的时候添加一些参数,其中重要的有:
SwaggerDoc:添加一个swagger document,主要用户存储生成出来的OpenAPI文档。以及一些文档基本信息,如:做者、描述、license等。
XXXFilter:自定义filter,XXX为Swagger中的对象,当XXX建立完成后,filter能够定义操做对XXX进行处理。
AddSecurityDefinition和AddSecurityRequirement:用于给Swagger添加验证的部分。
IncludeXmlComments:为OpenAPI提供注释内容的xml,须要在IDE里面配置生成对应的XML文件。(当vs中使用生成xml文档文件这个功能的时候,若是有方法没有添加注释,vs会有提示,若是要避免这个提示,能够在下图中的Suppress warnings中把1591禁掉。)this
RouteTemplate:UseSwagger中配置Swagger页面路由信息。
RoutePrefix:相似SharePoint中的host name,默认为swagger,若是不须要能够设置为“”。
SwaggerEndpoint:OpenAPI文件的访问URL,这个url和RouteTemplate以及SwaggerDoc的name必定要一致,否则就会有page not found的错。
当请求OpenAPI文件的时候,会从SwaggerEndpoint配置的url中配合RouteTemplate一块儿解析document的name。
下面是RouteTemplate的配置:url
1 app.UseSwagger(option => 2 { 3 option.RouteTemplate = string.Format("{0}/{1}", prefix, "{documentName}/swagger.json"); 4 });
解析document name的过程。spa
1 private bool RequestingSwaggerDocument(HttpRequest request, out string documentName) 2 { 3 documentName = null; 4 if (request.Method != "GET") return false; 5 6 var routeValues = new RouteValueDictionary(); 7 if (!_requestMatcher.TryMatch(request.Path, routeValues) || !routeValues.ContainsKey("documentName")) return false; 8 9 documentName = routeValues["documentName"].ToString(); 10 return true; 11 }