gpt4 book ai didi

swagger - Swashbuckle Swagger Asp.Net Core Pass Api Key 作为请求中的默认 header 值

转载 作者:行者123 更新时间:2023-12-04 12:10:48 26 4
gpt4 key购买 nike

我有基本的 Api,它接受 my-api-key 的默认 header 值和相应的值。

我试图让 Swagger UI 允许我输入一次标题进行授权,并让键/值随每个请求一起传递。

到目前为止,我只成功地将 header 作为参数显式添加到每个端点,但这并不理想。

相关代码片段:

        services.AddApiVersioning(
options =>
{
// reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
options.ReportApiVersions = true;
});
services.AddVersionedApiExplorer(
options =>
{
// add the versioned api explorer, which also adds IApiVersionDescriptionProvider service
// note: the specified format code will format the version as "'v'major[.minor][-status]"
options.GroupNameFormat = "'v'VVV";

// note: this option is only necessary when versioning by url segment. the SubstitutionFormat
// can also be used to control the format of the API version in route templates
options.SubstituteApiVersionInUrl = true;
});

services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api", Version = "v1" });
c.SwaggerDoc("v2", new OpenApiInfo { Title = "Api", Version = "v2" });

// this isn't ideal as I have to fill in the Api Key on ever request
//c.OperationFilter<ApiKeySwaggerFilter>();

c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
{
Type = SecuritySchemeType.ApiKey,
Name = "my-api-key",
In = ParameterLocation.Header
});

c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{ new OpenApiSecurityScheme()
{
// Type = SecuritySchemeType.ApiKey,
Name = ""
//In = ParameterLocation.Header
//Reference = new OpenApiReference()
//{
// Id = "myToken",
// Type = ReferenceType.SecurityScheme
//},
}, new string[] { }
}
});
});
app.UseSwagger();

app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Api v1");
c.SwaggerEndpoint("/swagger/v2/swagger.json", "Api v2");
});

我所在位置的对应图片:

enter image description here

对应的最小尖峰: https://github.com/aherrick/SwaggerSample

我觉得这很接近,但是如何让 Api Header 在每个请求上都得到传递,而不必强制用户在每个方法请求上填写参数。

最佳答案

通过以下部分更新弄清楚了:

           c.AddSecurityDefinition("ApiKey", new OpenApiSecurityScheme
{
Description = "Enter your Api Key below:",
Name = "my-api-key",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});

c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "ApiKey"
},
},
new List<string>()
}
});

关于swagger - Swashbuckle Swagger Asp.Net Core Pass Api Key 作为请求中的默认 header 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57796805/

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