直接在SwaggerConfig中设置请求头,这里请求头用的默认值apiKey,也可以自己定义一个
private const string swaggerApikey = "Authorization";
GlobalConfiguration.Configuration
.MessageHandlers.Add(new SwaggerMessageHandler());
GlobalConfiguration.Configuration .EnableSwagger(c => { c.ApiKey(swaggerApikey).Description("Filling bearer token here") .Name("Bearer") .In("header"); }) .EnableSwaggerUi(c => { c.EnableApiKeySupport(swaggerApikey, "header"); });
internal class SwaggerMessageHandler : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request.RequestUri.LocalPath.Equals("/swagger/docs/v1")) { var apikey = request.Headers.FirstOrDefault(x => x.Key.Equals(swaggerApikey)).Value?.FirstOrDefault(); if (!"apikey".Equals(apikey)) return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Forbidden)); } return base.SendAsync(request, cancellationToken); } }
标签:ApiKey,swaggerApikey,request,身份验证,Equals,apikey,net From: https://www.cnblogs.com/qingjiawen/p/17729772.html