背景
由於swagger不僅提供了自動實現接口文檔的說明而且支持頁面調試,告別postman等工具,無需開發人員手動寫api文檔,縮減開發成本得到大家廣泛認可
但是由於swagger沒有提供上傳文件的支持,所以只能靠開發人員自己實現。今天就來看看如何擴展swagger達到上傳文件的需求
動起小手手
1安裝swagger
nuget安裝Swashbuckle.AspNetCore.Swagger組件
2設置生成xml
右鍵項目>屬性>生成

相應的把其他需要生成文檔說明的項目也按上步驟進行設置xml
關鍵swagger代碼
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.PlatformAbstractions;
using Swashbuckle.AspNetCore.Swagger;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace Chaunce.Api.App_Start
{
/// <summary>
/// SwaggerConfig
/// </summary>
public class SwaggerConfig
{
/// <summary>
/// InitSwagger
/// </summary>
/// <param name="services"></param>
public static void InitSwagger(IServiceCollection services)
{
services.AddSwaggerGen(c =>
{
c.OperationFilter<SwaggerFileUploadFilter>();//增加文件過濾處理
var security = new Dictionary<string, IEnumerable<string>> { { "Bearer", new string[] { } }, };
c.AddSecurityRequirement(security);//添加一個必須的全局安全信息,和AddSecurityDefinition方法指定的方案名稱要一致,這里是Bearer。
var basePath = PlatformServices.Default.Application.ApplicationBasePath;// 獲取到應用程序的根路徑
var xmlApiPath = Path.Combine(basePath, "Chaunce.Api.xml");//api文件xml(在以上步驟2設置生成xml的路徑)
var xmlModelPath = Path.Combine(basePath, "Chaunce.ViewModels.xml");//請求modelxml
c.IncludeXmlComments(xmlApiPath);
c.IncludeXmlComments(xmlModelPath);
c.SwaggerDoc("v1", new Info
{
Title = "Chaunce數據接口",
Version = "v1",
Description = "這是一個webapi接口文檔說明",
TermsOfService = "None",
Contact = new Contact { Name = "Chaunce官網", Email = "info@Chaunce.com", Url = "http://blog.Chaunce.top/" },
License = new License
{
Name = "Swagger官網",
Url = "http://swagger.io/",
}
});
c.IgnoreObsoleteActions();
c.AddSecurityDefinition("Bearer", new ApiKeyScheme
{
Description = "權限認證(數據將在請求頭中進行傳輸) 參數結構: \"Authorization: Bearer {token}\"",
Name = "Authorization",//jwt默認的參數名稱
In = "header",//jwt默認存放Authorization信息的位置(請求頭中)
Type = "apiKey"
});//Authorization的設置
});
}
/// <summary>
/// ConfigureSwagger
/// </summary>
/// <param name="app"></param>
public static void ConfigureSwagger(IApplicationBuilder app)
{
app.UseSwagger();
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint.
app.UseSwagger(c =>
{
c.RouteTemplate = "docs/{documentName}/docs.json";//使中間件服務生成Swagger作為JSON端點(此處設置是生成接口文檔信息,可以理解為老技術中的webservice的soap協議的信息,暴露出接口信息的地方)
c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Info.Description = httpReq.Path);//請求過濾處理
});
app.UseSwaggerUI(c =>
{
c.RoutePrefix = "docs";//設置文檔首頁根路徑
c.SwaggerEndpoint("/docs/v1/docs.json", "V1");//此處配置要和UseSwagger的RouteTemplate匹配
//c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1");//默認終結點
c.InjectStylesheet("/swagger-ui/custom.css");//注入style文件
});
}
}
}
swagger過濾器
using Microsoft.AspNetCore.Http;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Chaunce.Api.Help
{
/// <summary>
/// swagger文件過濾器
/// </summary>
public class SwaggerFileUploadFilter : IOperationFilter
{
/// <summary>
/// swagger過濾器(此處的Apply會被swagger的每個接口都調用生成文檔說明,所以在此處可以對每一個接口進行過濾操作)
/// </summary>
/// <param name="operation"></param>
/// <param name="context"></param>
public void Apply(Operation operation, OperationFilterContext context)
{
if (!context.ApiDescription.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase) &&
!context.ApiDescription.HttpMethod.Equals("PUT", StringComparison.OrdinalIgnoreCase))
{
return;
}
var apiDescription = context.ApiDescription;
var parameters = context.ApiDescription.ParameterDescriptions.Where(n => n.Type == typeof(IFormFileCollection) || n.Type == typeof(IFormFile)).ToList();//parameterDescriptions包含了每個接口所帶所有參數信息
if (parameters.Count() <= 0)
{
return;
}
operation.Consumes.Add("multipart/form-data");
foreach (var fileParameter in parameters)
{
var parameter = operation.Parameters.Single(n => n.Name == fileParameter.Name);
operation.Parameters.Remove(parameter);
operation.Parameters.Add(new NonBodyParameter
{
Name = parameter.Name,
In = "formData",
Description = parameter.Description,
Required = parameter.Required,
Type = "file",
//CollectionFormat = "multi"
});
}
}
}
}


打開瀏覽器http://localhost:8532/docs/


還沒有結束,我們看看如何讓Jwt的認證信息自動存在請求頭免去每次手動塞
點擊


(實際情況是填寫的信息格式是:Bearer *************(Bearer與后面信息有一個空格))
此時隨意訪問任何api,都會將以上信息自動塞入header中進行請求,如下驗證

至此目的都達到了
參考:
http://www.cnblogs.com/Erik_Xu/p/8904854.html#3961244
https://github.com/domaindrivendev/Swashbuckle

