asp.net core Swagger 首字母小写和BearToken支持
开始
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 = new OpenApiSecurityScheme() { 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/