swagger上傳文件并支持jwt認(rèn)證的實現(xiàn)方法
什么是 Swagger?
Swagger的目標(biāo)是為REST APIs 定義一個標(biāo)準(zhǔn)的,與語言無關(guān)的接口,使人和計算機在看不到源碼或者看不到文檔或者不能通過網(wǎng)絡(luò)流量檢測的情況下能發(fā)現(xiàn)和理解各種服務(wù)的功能。當(dāng)服務(wù)通過Swagger定義,消費者就能與遠(yuǎn)程的服務(wù)互動通過少量的實現(xiàn)邏輯。類似于低級編程接口,Swagger去掉了調(diào)用服務(wù)時的很多猜測。
背景
由于swagger不僅提供了自動實現(xiàn)接口文檔的說明而且支持頁面調(diào)試,告別postman等工具,無需開發(fā)人員手動寫api文檔,縮減開發(fā)成本得到大家廣泛認(rèn)可但是由于swagger沒有提供上傳文件的支持,所以只能靠開發(fā)人員自己實現(xiàn)。今天就來看看如何擴展swagger達(dá)到上傳文件的需求
動起小手手
1安裝swagger
nuget安裝Swashbuckle.AspNetCore.Swagger組件
2設(shè)置生成xml
右鍵項目>屬性>生成
相應(yīng)的把其他需要生成文檔說明的項目也按上步驟進行設(shè)置xml
關(guān)鍵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;// 獲取到應(yīng)用程序的根路徑 var xmlApiPath = Path.Combine(basePath, "Chaunce.Api.xml");//api文件xml(在以上步驟2設(shè)置生成xml的路徑) var xmlModelPath = Path.Combine(basePath, "Chaunce.ViewModels.xml");//請求modelxml c.IncludeXmlComments(xmlApiPath); c.IncludeXmlComments(xmlModelPath); c.SwaggerDoc("v1", new Info { Title = "Chaunce數(shù)據(jù)接口", Version = "v1", Description = "這是一個webapi接口文檔說明", TermsOfService = "None", Contact = new Contact { Name = "Chaunce官網(wǎng)", Email = "info@Chaunce.com", Url = "http://blog.Chaunce.top/" }, License = new License { Name = "Swagger官網(wǎng)", Url = "http://swagger.io/", } }); c.IgnoreObsoleteActions(); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "權(quán)限認(rèn)證(數(shù)據(jù)將在請求頭中進行傳輸) 參數(shù)結(jié)構(gòu): \"Authorization: Bearer {token}\"", Name = "Authorization",//jwt默認(rèn)的參數(shù)名稱 In = "header",//jwt默認(rèn)存放Authorization信息的位置(請求頭中) Type = "apiKey" });//Authorization的設(shè)置 }); } /// <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";//使中間件服務(wù)生成Swagger作為JSON端點(此處設(shè)置是生成接口文檔信息,可以理解為老技術(shù)中的webservice的soap協(xié)議的信息,暴露出接口信息的地方) c.PreSerializeFilters.Add((swaggerDoc, httpReq) => swaggerDoc.Info.Description = httpReq.Path);//請求過濾處理 }); app.UseSwaggerUI(c => { c.RoutePrefix = "docs";//設(shè)置文檔首頁根路徑 c.SwaggerEndpoint("/docs/v1/docs.json", "V1");//此處配置要和UseSwagger的RouteTemplate匹配 //c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1");//默認(rèn)終結(jié)點 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的每個接口都調(diào)用生成文檔說明,所以在此處可以對每一個接口進行過濾操作) /// </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包含了每個接口所帶所有參數(shù)信息 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/
還沒有結(jié)束,我們看看如何讓Jwt的認(rèn)證信息自動存在請求頭免去每次手動塞
點擊
(實際情況是填寫的信息格式是:Bearer *************(Bearer與后面信息有一個空格))
此時隨意訪問任何api,都會將以上信息自動塞入header中進行請求,如下驗證
至此目的都達(dá)到了
參考:
http://www.dbjr.com.cn/article/140105.htm
https://github.com/domaindrivendev/Swashbuckle
總結(jié)
以上所述是小編給大家介紹的swagger上傳文件并支持jwt認(rèn)證的實現(xiàn)方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
ASP.NET Core 數(shù)據(jù)保護(Data Protection)上篇
這篇文章主要為大家詳細(xì)介紹了ASP.NET Core 數(shù)據(jù)保護(Data Protection),具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09使用asp.net MVC4中的Bundle遇到的問題及解決辦法分享
這篇文章主要介紹了使用asp.net MVC4中的Bundle遇到的問題及解決辦法,需要的朋友可以參考下2014-02-02asp.net c#采集需要登錄頁面的實現(xiàn)原理及代碼
當(dāng)我們采集頁面的時候,如果被采集的網(wǎng)站需要登錄才能采集,原理搞清楚了,就好辦了,我們所要做的僅僅是在采集的時候(或者說HttpWebRequest提交數(shù)據(jù)的時候),將Cookie信息放入Http請求頭里面就可以了,感興趣的朋友可以了解下,或許對你有所幫助2013-02-02asp.net Repeater取得CheckBox選中的某行某個值
Repeater取得CheckBox選中的某行某個值的實現(xiàn)代碼2008-07-07使用HttpClient增刪改查ASP.NET Web API服務(wù)
這篇文章介紹了使用HttpClient增刪改查ASP.NET Web API服務(wù)的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-10-10ASP.NET Core MVC學(xué)習(xí)之視圖組件(View Component)
這篇文章主要給大家介紹了關(guān)于ASP.NET Core MVC學(xué)習(xí)之視圖組件(View Component)的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用ASP.NET Core MVC具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08