asp.net core 3.0中使用swagger的方法與問題
Intro#
上次更新了 asp.net core 3.0 簡單的記錄了一下 swagger 的使用,那個項目的 api 比較簡單,都是匿名接口不涉及到認(rèn)證以及 api 版本控制,最近把另外一個 api 項目升級到了 3.0,還是遇到了一些問題,這里單獨(dú)寫一篇文章介紹,避免踩坑。
Swagger 基本使用#
swagger 服務(wù)注冊:
services.AddSwaggerGen(option => { option.SwaggerDoc("sparktodo", new OpenApiInfo { Version = "v1", Title = "SparkTodo API", Description = "API for SparkTodo", Contact = new OpenApiContact() { Name = "WeihanLi", Email = "weihanli@outlook.com" } }); // include document file option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{typeof(Startup).Assembly.GetName().Name}.xml"), true); });
中間件配置:
//Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); //Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint app.UseSwaggerUI(option => { option.SwaggerEndpoint("/swagger/sparktodo/swagger.json", "sparktodo Docs"); option.RoutePrefix = string.Empty; option.DocumentTitle = "SparkTodo API"; });
為 Swagger 添加 Bearer Token 認(rèn)證#
services.AddSwaggerGen(option => { // ... // Add security definitions option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme() { Description = "Please enter into field the word 'Bearer' followed by a space and the JWT value", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey, }); option.AddSecurityRequirement(new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference() { Id = "Bearer", Type = ReferenceType.SecurityScheme } }, Array.Empty<string>() } }); });
支持多個 ApiVersion#
services.AddApiVersioning(options => { options.AssumeDefaultVersionWhenUnspecified = true; options.DefaultApiVersion = ApiVersion.Default; options.ReportApiVersions = true; }); services.AddSwaggerGen(option => { // ... option.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "API V1" }); option.SwaggerDoc("v2", new OpenApiInfo { Version = "v2", Title = "API V2" }); option.DocInclusionPredicate((docName, apiDesc) => { var versions = apiDesc.CustomAttributes() .OfType<ApiVersionAttribute>() .SelectMany(attr => attr.Versions); return versions.Any(v => $"v{v.ToString()}" == docName); }); option.OperationFilter<RemoveVersionParameterOperationFilter>(); option.DocumentFilter<SetVersionInPathDocumentFilter>(); });
自定義 Api version 相關(guān)的 OperationFilter:
public class SetVersionInPathDocumentFilter : IDocumentFilter { public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context) { var updatedPaths = new OpenApiPaths(); foreach (var entry in swaggerDoc.Paths) { updatedPaths.Add( entry.Key.Replace("v{version}", swaggerDoc.Info.Version), entry.Value); } swaggerDoc.Paths = updatedPaths; } } public class RemoveVersionParameterOperationFilter : IOperationFilter { public void Apply(OpenApiOperation operation, OperationFilterContext context) { // Remove version parameter from all Operations var versionParameter = operation.Parameters.Single(p => p.Name == "version"); operation.Parameters.Remove(versionParameter); } }
中間件配置:
//Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); //Enable middleware to serve swagger-ui (HTML, JS, CSS etc.), specifying the Swagger JSON endpoint app.UseSwaggerUI(option => { option.SwaggerEndpoint("/swagger/v2/swagger.json", "V2 Docs"); option.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs"); option.RoutePrefix = string.Empty; option.DocumentTitle = "SparkTodo API"; });
最終 swagger 效果
Memo#
上面的配置來自 https://github.com/WeihanLi/SparkTodo 這個項目,要獲取代碼可以參考這個項目
Reference#
- https://github.com/domaindrivendev/Swashbuckle.AspNetCore/tree/master/test/WebSites/MultipleVersions/Swagger
- https://stackoverflow.com/questions/58197244/swaggerui-with-netcore-3-0-bearer-token-authorization
- https://github.com/domaindrivendev/Swashbuckle.AspNetCore/issues/1295
- https://github.com/WeihanLi/SparkTodo
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。
相關(guān)文章
asp.net基于Calendar實(shí)現(xiàn)blog日歷功能示例
這篇文章主要介紹了asp.net基于Calendar實(shí)現(xiàn)blog日歷功能,涉及asp.net使用Calendar控件操作日期與時間相關(guān)運(yùn)算技巧,需要的朋友可以參考下2017-07-07Asp.net 中mvc 實(shí)現(xiàn)超時彈窗后跳轉(zhuǎn)功能
這篇文章主要介紹了Asp.net 中mvc 實(shí)現(xiàn)超時彈窗后跳轉(zhuǎn)功能,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-02-02asp.net 字符串、二進(jìn)制、編碼數(shù)組轉(zhuǎn)換函數(shù)
字符串和二進(jìn)制數(shù)組轉(zhuǎn)換、將HTML文件顯示為頁面的一部分、UTF8和GB2312之間的轉(zhuǎn)換2010-01-01在.NET?MAUI應(yīng)用中配置應(yīng)用生命周期事件
本文詳細(xì)講解了在.NET?MAUI應(yīng)用中配置應(yīng)用生命周期事件的方法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03asp.net ASPxTextBox等控件實(shí)現(xiàn)"回車模擬Tab"的 常用代碼整理
今天我要實(shí)現(xiàn)一些編輯框如ASPxTextBox、ASPxComboBox等控件回車模擬Tab的功能。這沒辦法,用戶用慣了回車,討厭按Tab來移動焦點(diǎn)(鼠標(biāo)點(diǎn)擊更麻煩)。2010-03-03Silverlight中同步調(diào)用WebClient的解決辦法,是同步!
如何建立web服務(wù)并引用的細(xì)節(jié),不是本文的介紹的目標(biāo),不再贅述。在silverlight調(diào)用服務(wù)器端服務(wù)的時候,默認(rèn)情況下是進(jìn)行異步調(diào)用的2011-04-04asp.net下無法循環(huán)綁定投票的標(biāo)題和選項的解決方法
asp.net下無法循環(huán)綁定投票的標(biāo)題和選項與無法循環(huán)獲得用戶的選擇的解決方法。2010-12-12