gpt4 book ai didi

c# - 如何在 Swashbuckle 中添加标题文档?

转载 作者:可可西里 更新时间:2023-11-01 09:11:44 27 4
gpt4 key购买 nike

我正在使用 Swashbuckle 库。目前没有它的 stackoverflow 标签。

我不太明白这里的文档:https://github.com/domaindrivendev/Swashbuckle/blob/master/README.md

标题为“描述安全/授权方案”的部分提到了一段代码

   c.ApiKey("apiKey")
.Description("API Key Authentication")
.Name("apiKey")
.In("header");

但是,当我包含这个时,什么也没有发生。我也希望它只出现在某些 API 方法上。它确实提到了

"need to be coupled with a corresponding "security" property at the document "

但是我不明白这个。

谁能解释一下?

最佳答案

我遇到了同样的问题,然后这样解决了:

在 SwaggerConfig:

var applyApiKeySecurity = new ApplyApiKeySecurity(
key: "ServiceBusToken",
name: "Authorization",
description: "Service Bus Token, e.g. 'SharedAccessSignature sr=...&sig=...&se=...&skn=...'",
@in: "header"
);
applyApiKeySecurity.Apply(c);

ApplyApiKeySecurity:

public class ApplyApiKeySecurity : IDocumentFilter, IOperationFilter
{
public ApplyApiKeySecurity(string key, string name, string description, string @in)
{
Key = key;
Name = name;
Description = description;
In = @in;
}

public string Description { get; private set; }

public string In { get; private set; }

public string Key { get; private set; }

public string Name { get; private set; }

public void Apply(SwaggerDocument swaggerDoc, SchemaRegistry schemaRegistry, System.Web.Http.Description.IApiExplorer apiExplorer)
{
IList<IDictionary<string, IEnumerable<string>>> security = new List<IDictionary<string, IEnumerable<string>>>();
security.Add(new Dictionary<string, IEnumerable<string>> {
{Key, new string[0]}
});

swaggerDoc.security = security;
}

public void Apply(Operation operation, SchemaRegistry schemaRegistry, System.Web.Http.Description.ApiDescription apiDescription)
{
operation.parameters = operation.parameters ?? new List<Parameter>();
operation.parameters.Add(new Parameter
{
name = Name,
description = Description,
@in = In,
required = true,
type = "string"
});
}

public void Apply(Swashbuckle.Application.SwaggerDocsConfig c)
{
c.ApiKey(Key)
.Name(Name)
.Description(Description)
.In(In);
c.DocumentFilter(() => this);
c.OperationFilter(() => this);
}
}

然后 swagger 文件具有安全定义:

"securityDefinitions":{  
"ServiceBusToken":{
"type":"apiKey",
"description":"Service Bus Token, e.g. 'SharedAccessSignature sr=...&sig=...&se=...&skn=...'",
"name":"Authorization",
"in":"header"
}
}

应用于文档级别的所有操作:

"security":[  
{
"ServiceBusToken":[]
}
]

并且所有操作都分配了 header 参数:

"parameters":[  
{
"name":"Authorization",
"in":"header",
"description":"Service Bus Token, e.g. 'SharedAccessSignature sr=...&sig=...&se=...&skn=...'",
"required":true,
"type":"string"
}
]

关于c# - 如何在 Swashbuckle 中添加标题文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28865814/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com