为网络api中的特定版本而大张旗鼓地添加Bearer令牌选项

问题描述 投票:1回答:2

我正在Web API应用程序中使用swagger。我有api版本,我想将Bearer令牌选项应用于版本2,两个版本都没有进行验证。这是我的代码

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

    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey,         
    });
});

enter image description hereenter image description here

c# asp.net-web-api swagger swagger-ui
2个回答
0
投票

您可以安装NSwag.AspNetCore并添加具有不同版本的不同选项。

services.AddSwaggerDocument(a =>
{
    a.DocumentName = "v1";
    a.Version = "v1";
});

services.AddSwaggerDocument(a =>
{
    a.DocumentName = "v2";
    a.Version = "v2";
    a.AddSecurity("bearer", new NSwag.OpenApiSecurityScheme
    {
        Description = "jwt",
        In = NSwag.OpenApiSecurityApiKeyLocation.Header,
        Type = NSwag.OpenApiSecuritySchemeType.ApiKey,
        Scheme = "bearer"
    });
});
app.UseOpenApi();
app.UseSwaggerUi3();

您可以在Microsoft Docs中了解更多信息。


0
投票

解决此问题的另一种方法,我假设您具有控制器版本v1的前缀作为前缀,那么您可以做的是:

public class AuthorizationHeaderParameterOperationFilter : IOperationFilter
{
    public void Apply(OpenApiOperation operation, OperationFilterContext context)
    {
        if (operation.Parameters == null)
            operation.Parameters = new List<OpenApiParameter>();

        if (context.ApiDescription.RelativePath.StartsWith("v2"))
        {
            operation.Parameters.Add(new OpenApiParameter()
            {
                @In = ParameterLocation.Header,
                Description =
                    "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                Name = "Authorization",
            });
        }

    }
}

并使用它

services.ConfigureSwaggerGen(options =>
{
    options.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
});

这只会将Bearer字段添加到v2端点。

© www.soinside.com 2019 - 2024. All rights reserved.