我've a web api2 project, where I'已实现swashbuckle用于测试和记录我的Web服务 . 我试图在SwaggerDocsConfig中设置apiKey进行身份验证,但是如果我想添加另一个apiKey( apiKey 和 appId ),我就无法使其正常工作 .
我在swagger doc中读到了可能,但我不知道如何用swashbuckle以这种方式配置swagger文档 .
Swagger文档应该如何
securityDefinitions:
apiKey:
type: apiKey
in: header
name: X-API-KEY
appId:
type: apiKey
in: header
name: X-APP-ID
security:
- apiKey: []
appId: []
当我在项目中启用swagger时,我试图简单地添加另一个ApiKey(参见上面的代码),但它没有用 .
GlobalConfiguration.Configuration.EnableSwagger(swagger =>
{
swagger.RootUrl(req => req.RequestUri.GetLeftPart(UriPartial.Authority).TrimEnd('/') + req.GetRequestContext().VirtualPathRoot.TrimStart('/'));
swagger.PrettyPrint();
c.SingleApiVersion("v1", "Project.WebApi");
swagger.ApiKey("apiKey") //First ApiKey
.Description("API Key Authentication")
.Name("Authorization")
.In("header");
swagger.ApiKey("apiId") //Second ApiKey
.Description("API Key Authentication")
.Name("Authorization") //Same Schema
.In("header");
swagger.IncludeXmlComments(string.Format(@"{0}\bin\Project.WebApi.XML", System.AppDomain.CurrentDomain.BaseDirectory));
swagger.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
})
.EnableSwaggerUi(swagger =>
{
swagger.DocumentTitle("Project API");
swagger.DocExpansion(DocExpansion.List);
swagger.EnableDiscoveryUrlSelector();
swagger.EnableApiKeySupport("Authorization", "header");
});
是否可以使用Swashbuckle,或者我必须注入一个js脚本并从客户端执行?
谢谢
2 回答
我刚用Swagger-Net进行了测试,看起来效果很好......
这是一个功能齐全的例子:
http://nhc-noaa.azurewebsites.net/swagger/ui/index?filter=&docExpansion=list
一旦你输入apiKey和appId,curl看起来像这样:
完全披露我是Swagger-Net的所有者,实现非常类似于swashbuckle,我只是尝试简化了很多设置,EnableApiKeySupport是我完全删除的那些东西之一,做你问的所有你需要的东西是:
完整代码在这里:
https://github.com/heldersepu/nhc-noaa/blob/master/nhc-noaa/App_Start/SwaggerConfig.cs
@ HelderSepu的响应有效,但我找到了另一种解决方案,可能可以帮助某些人无法从Swashbuckle转移到Swagger-Net .
可以创建自定义OperationFilter对象,您可以通过这种方式在每个调用中设置其他参数:
然后,当您以这种方式配置Swagger时,您必须实现它:
我希望这可以帮助别人 .