2023年6月20日发(作者:)
Swagger在header中添加token概述平常做项⽬使⽤mvc+webapi,采取前后端分离的⽅式,后台提供API接⼝给前端开发⼈员。这个过程中遇到⼀个问题后台开发⼈员怎么提供接⼝说明⽂档给前端开发⼈员。为了解决这个问题,项⽬中引⽤swagger(我⽐较喜欢戏称为“丝袜哥”)。列出所有API控制器和控制器描述问题那么既然是api,肯定涉及到安全验证问题,那么怎么在测试⽂档增加添加Token安全验证呢;代码实现下⾯我们来看看1、定义swagger请求头•••••••••••••••••••••••••••••••••••••••••••••••••using ization; using r; rGen; using c; using ; tion; namespace {/// /// swagger请求头///public class HttpHeaderOperationFilter : IOperationFilter{/// ////// /// /// public void Apply(Operation operation,OperationFilterContext context){#region 新⽅法if (ters == null){ters = newList;}if (MethodInfo(out MethodInfo methodInfo)){if((t => uteType != typeof(AllowAnonymousAttribute))&& !((t => uteType == typeof(AuthorizeAttribute)))){(new NonBodyParameter{Name = "Authorization",In = "header",Type = "string",Required =true,Deion = "请输⼊Token,格式为bearer XXX"});}}#endregion 新⽅法}}}2、在ConfigureServices⽅法添加OperationFilter /// ////// /// // This method gets called by theruntime. Use this method to add services to the IServiceProviderConfigureServices(IServiceCollection services){e(ent);nOptions(options =>{lueHandling =;(eTimeConverter{DateTimeFormat = "yyyy-MM-dd HH:mm:ss"});//⼩写ctResolver = newCamelCasePropertyNamesContractResolver;ctResolver = newDefaultContractResolver;// // rmatString = "yyyy-MM-dd";});//SerializerFormatters;//DataContractSerializerFormatters;ging;s(options=>icy("AllowSameDomain", builder =>nyHeader));ure(options =>{(new CorsAuthorizationFilterFactory("AllowSameDomain"));});#ggerGen(c =>{rDoc("v1", new Info{Version = "v1",Title = "接⼝⽂档",Deion = "接⼝⽂档-基础",TermsOfService = "/terms",Contact = new Contact{Name = "XXX1111",Email ="**************",Url="/terms"},License=newLicense{Name="UseunderLICX",Url="/license",}});rDoc("v2", new Info{Version = "v2",Title = "接⼝⽂档",Deion = "接⼝⽂档-基础",TermsOfService = "/terms",Contact = new Contact{Name = "XXX2222",Email ="**************",Url="/terms"},License=newLicense{Name="UseunderLICX",Url="/license",}});ionFilter;ntFilter;varxmlFile = $"{}.xml";var xmlPath =e(rectory,xmlFile);eXmlComments(xmlPath);eXmlComments(e(rectory,$""));});#endregion Swagger#region MiniProfilerif((Configuration["IsUseMiniProfiler"])){///lwqlun/p/iProfiler(options =>asePath ="/profiler").AddEntityFramework;}#endregion ontext(options =>ql(Configuration["Data:MyCat:ConnectionString"]));var container = tofac(services,cutingAssembly);return new AutofacServiceProvider(container);}3、定义⼀个ActionFilterAttributeusing ;using ;s;using ;using pal;{/// /// 权限/// public class BasicAuth :ActionFilterAttribute{/// ////// /// public override voidOnActionExecuting(ActionExecutingContext context){if (t != null &&s != null && s["Authorization"].Count > 0){vartoken = s["Authorization"];if (OrWhiteSpace(token)){ResultDto meta =("Unauthorized");JsonResult json = new JsonResult(new{Meta = meta});JsonSerializerSettings jsetting =new JsonSerializerSettings;lueHandling = ;(newnew JsonSerializerSettings;lueHandling = ;(eTimeConverter{DateTimeFormat = "yyyy-MM-ddHH:mm:ss"});izerSettings = jsetting;tType = "application/json; charset=utf-8"; =json;}else{GenericIdentity ci = new GenericIdentity(token); = "conan1111111"; = newGenericPrincipal(ci, null);}}else{ResultDto meta = ("Unauthorized");JsonResult json = newJsonResult(new{Meta = meta});JsonSerializerSettings jsetting = newJsonSerializerSettings;lueHandling = ;(eTimeConverter{DateTimeFormat = "yyyy-MM-ddHH:mm:ss"});izerSettings = jsetting;tType = "application/json; charset=utf-8"; =json;}onExecuting(context);}}}4、最后在需要的地⽅使⽤ [BasicAuth] //////添加/////////主键id [ BasicAuth] [ ModelValidationAttribute] [ApiExplorerSettings(GroupName = "v1") ] [ HttpPost, Route( "Create") ] publicasyncTask>CreateAsync([FromBody]CreateWebConfigDto model) {returnawait_Async(model,tUser); }效果我们就可以看到Authorization - 请输⼊Token,格式为bearer XXX源码下载源码地址:/conanl5566/Sampleproject/tree/master/src/03%20Host/
2023年6月20日发(作者:)
Swagger在header中添加token概述平常做项⽬使⽤mvc+webapi,采取前后端分离的⽅式,后台提供API接⼝给前端开发⼈员。这个过程中遇到⼀个问题后台开发⼈员怎么提供接⼝说明⽂档给前端开发⼈员。为了解决这个问题,项⽬中引⽤swagger(我⽐较喜欢戏称为“丝袜哥”)。列出所有API控制器和控制器描述问题那么既然是api,肯定涉及到安全验证问题,那么怎么在测试⽂档增加添加Token安全验证呢;代码实现下⾯我们来看看1、定义swagger请求头•••••••••••••••••••••••••••••••••••••••••••••••••using ization; using r; rGen; using c; using ; tion; namespace {/// /// swagger请求头///public class HttpHeaderOperationFilter : IOperationFilter{/// ////// /// /// public void Apply(Operation operation,OperationFilterContext context){#region 新⽅法if (ters == null){ters = newList;}if (MethodInfo(out MethodInfo methodInfo)){if((t => uteType != typeof(AllowAnonymousAttribute))&& !((t => uteType == typeof(AuthorizeAttribute)))){(new NonBodyParameter{Name = "Authorization",In = "header",Type = "string",Required =true,Deion = "请输⼊Token,格式为bearer XXX"});}}#endregion 新⽅法}}}2、在ConfigureServices⽅法添加OperationFilter /// ////// /// // This method gets called by theruntime. Use this method to add services to the IServiceProviderConfigureServices(IServiceCollection services){e(ent);nOptions(options =>{lueHandling =;(eTimeConverter{DateTimeFormat = "yyyy-MM-dd HH:mm:ss"});//⼩写ctResolver = newCamelCasePropertyNamesContractResolver;ctResolver = newDefaultContractResolver;// // rmatString = "yyyy-MM-dd";});//SerializerFormatters;//DataContractSerializerFormatters;ging;s(options=>icy("AllowSameDomain", builder =>nyHeader));ure(options =>{(new CorsAuthorizationFilterFactory("AllowSameDomain"));});#ggerGen(c =>{rDoc("v1", new Info{Version = "v1",Title = "接⼝⽂档",Deion = "接⼝⽂档-基础",TermsOfService = "/terms",Contact = new Contact{Name = "XXX1111",Email ="**************",Url="/terms"},License=newLicense{Name="UseunderLICX",Url="/license",}});rDoc("v2", new Info{Version = "v2",Title = "接⼝⽂档",Deion = "接⼝⽂档-基础",TermsOfService = "/terms",Contact = new Contact{Name = "XXX2222",Email ="**************",Url="/terms"},License=newLicense{Name="UseunderLICX",Url="/license",}});ionFilter;ntFilter;varxmlFile = $"{}.xml";var xmlPath =e(rectory,xmlFile);eXmlComments(xmlPath);eXmlComments(e(rectory,$""));});#endregion Swagger#region MiniProfilerif((Configuration["IsUseMiniProfiler"])){///lwqlun/p/iProfiler(options =>asePath ="/profiler").AddEntityFramework;}#endregion ontext(options =>ql(Configuration["Data:MyCat:ConnectionString"]));var container = tofac(services,cutingAssembly);return new AutofacServiceProvider(container);}3、定义⼀个ActionFilterAttributeusing ;using ;s;using ;using pal;{/// /// 权限/// public class BasicAuth :ActionFilterAttribute{/// ////// /// public override voidOnActionExecuting(ActionExecutingContext context){if (t != null &&s != null && s["Authorization"].Count > 0){vartoken = s["Authorization"];if (OrWhiteSpace(token)){ResultDto meta =("Unauthorized");JsonResult json = new JsonResult(new{Meta = meta});JsonSerializerSettings jsetting =new JsonSerializerSettings;lueHandling = ;(newnew JsonSerializerSettings;lueHandling = ;(eTimeConverter{DateTimeFormat = "yyyy-MM-ddHH:mm:ss"});izerSettings = jsetting;tType = "application/json; charset=utf-8"; =json;}else{GenericIdentity ci = new GenericIdentity(token); = "conan1111111"; = newGenericPrincipal(ci, null);}}else{ResultDto meta = ("Unauthorized");JsonResult json = newJsonResult(new{Meta = meta});JsonSerializerSettings jsetting = newJsonSerializerSettings;lueHandling = ;(eTimeConverter{DateTimeFormat = "yyyy-MM-ddHH:mm:ss"});izerSettings = jsetting;tType = "application/json; charset=utf-8"; =json;}onExecuting(context);}}}4、最后在需要的地⽅使⽤ [BasicAuth] //////添加/////////主键id [ BasicAuth] [ ModelValidationAttribute] [ApiExplorerSettings(GroupName = "v1") ] [ HttpPost, Route( "Create") ] publicasyncTask>CreateAsync([FromBody]CreateWebConfigDto model) {returnawait_Async(model,tUser); }效果我们就可以看到Authorization - 请输⼊Token,格式为bearer XXX源码下载源码地址:/conanl5566/Sampleproject/tree/master/src/03%20Host/
发布评论