關于 Swagger
Swagger能成為最受歡迎的REST APIs文檔生成工具之一,有以下幾個原因:
- Swagger 可以生成一個具有互動性的API控制臺,開發者可以用來快速學習和嘗試API。
- Swagger 可以生成客戶端SDK代碼用于各種不同的平臺上的實現。
- Swagger 文件可以在許多不同的平臺上從代碼注釋中自動生成。
- Swagger 有一個強大的社區,里面有許多強悍的貢獻者。
Swagger 文檔提供了一個方法,使我們可以用指定的 JSON摘要來描述你的 API,包括了比如 names、order 等 API 信息。
1、安裝Swashbuckle.AspNetCore
using Swashbuckle.AspNetCore.Swagger;
public void ConfigureServices(IServiceCollection services){//注冊Swagger生成器,定義一個和多個Swagger 文檔services.AddSwaggerGen(c =>{c.SwaggerDoc("v1", new Info { Title = "My API", Version = "v1" });//設置版本號,標題var xmlPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "SwaggerApi.xml");//為Swagger設置xml文檔注釋路徑c.IncludeXmlComments(xmlPath);//只有設置了xmlm文檔的路徑生成的文檔才會有注釋c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader參數 });services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);}
2、啟用中間件服務
public void Configure(IApplicationBuilder app, IHostingEnvironment env){if (env.IsDevelopment()){app.UseDeveloperExceptionPage();}else{app.UseHsts();}//啟用中間件服務生成Swagger作為JSON終結點 app.UseSwagger();//啟用中間件服務對swagger-ui,指定Swagger JSON終結點app.UseSwaggerUI(c =>{c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");c.RoutePrefix = string.Empty;});app.UseHttpsRedirection();app.UseMvc();}
?
3、新建HttpHeaderOperation
public void Apply(Operation operation, OperationFilterContext context){if (operation.Parameters == null){operation.Parameters = new List<IParameter>();}var actionAttrs = context.ApiDescription.ActionAttributes();var isAuthorized = actionAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));if (isAuthorized == false) //提供action都沒有權限特性標記,檢查控制器有沒有 {var controllerAttrs = context.ApiDescription.ControllerAttributes();isAuthorized = controllerAttrs.Any(a => a.GetType() == typeof(AuthorizeAttribute));}var isAllowAnonymous = actionAttrs.Any(a => a.GetType() == typeof(AllowAnonymousAttribute));if (isAuthorized && isAllowAnonymous == false){operation.Parameters.Add(new NonBodyParameter(){Name = "Authorization", //添加Authorization頭部參數In = "header",Type = "string",Required = false,Description = "access token"});}}public void Apply(SwaggerDocument swaggerDoc, DocumentFilterContext context){throw new NotImplementedException();}
4、配置XML文檔路徑
?5、地址欄輸入http://localhost:{port}/swagger/index.html
?