Swagger UI in AspNetCore WebAPI

Swagger其實包含了三個部分,分別是Swagger Editor文檔接口編輯器,根據接口文檔生成code的Swagger Codegen,以及生成在線文檔的Swagger UI。
在AspNetCore中一般使用Microsoft封裝的Swashbuckle來使用Swagger UI,這是一個AspNetCore的中間件。和其餘中間件同樣都是分爲register和use兩個部分。json

  

Installation


VS中很簡單,直接用NuGet安裝Swashbuckle.AspNetCore便可。app

 

 或者使用命令行: dotnet add package --version xxx Swashbuckle.AspNetCore編輯器

 

Register


 全部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進行處理。
AddSecurityDefinitionAddSecurityRequirement:用於給Swagger添加驗證的部分。
IncludeXmlComments:爲OpenAPI提供註釋內容的xml,須要在IDE裏面配置生成對應的XML文件。(當vs中使用生成xml文檔文件這個功能的時候,若是有方法沒有添加註釋,vs會有提示,若是要避免這個提示,能夠在下圖中的Suppress warnings中把1591禁掉。)this

 

 

 Use

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 }
相關文章
相關標籤/搜索