asp.net core Swagger 首字母小寫和BearToken支援
阿新 • • 發佈:2021-01-21
開始
asp.net core webapi Swagger按照官網步驟搭建之後,也引用了Json.net 作為返回值的序列化支援。
AddNewtonsoftJson(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.SerializerSettings.ContractResolver = new DefaultContractResolver(); options.SerializerSettings.NullValueHandling = NullValueHandling.Include; });
但 swagger介面的入參和返回值 還是預設首字母小寫。
通過網上查詢,發現swagger內部還是應用了預設的System.Text.Json,這樣就導致swagger介面和我們的引數不一致。
方案
應用nuget上對應的package:
Install-Package Swashbuckle.AspNetCore.Newtonsoft
程式碼中這樣引用:
services.AddSwaggerGenNewtonsoftSupport();
通過官網步驟的設定,預設是沒有對BearkToken的設定,其實swagger是支援的,需要加以下程式碼:
var securityScheme = newOpenApiSecurityScheme() { Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"", Name = "Authorization", //引數新增在頭部 In = ParameterLocation.Header, //使用Authorize頭部 Type = SecuritySchemeType.Http, //內容為以 bearer開頭 Scheme = "bearer", BearerFormat = "JWT" }; var securityRequirement = new OpenApiSecurityRequirement { { new OpenApiSecurityScheme { Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "bearerAuth" } }, new string[] {} } }; c.AddSecurityDefinition("bearerAuth", securityScheme); c.AddSecurityRequirement(securityRequirement);
結束
以上就是對swagger操作的一些記錄,這裡做些記錄,參考資料:
http://www.manongjc.com/detail/17-paoieyapwcadthj.html
https://dotnetcoretutorials.com/2020/01/31/using-swagger-in-net-core-3/