如何使用Swagger(Swashbuckle)调用web api时传递自定义标头

Kir*_*n R 10 asp.net-web-api swagger-ui

我们使用Swashbuckle记录我们的web apis并使用它来测试我们的web apis.我想知道如何使用Swagger UI为每个请求传递具有不同值的多个自定义标头.

我在互联网上看到了如下的答案,在Swagger UI中传递了一个标题但却无法理解它.令人困惑的是SwaggerExtensions文件.此文件的目的是什么?为什么在js文件的限定名称中提及此文件.

1.添加名为"SwaggerExtensions"的新文件,然后添加名为"onComplete.js"的新JS文件,您必须将此文件的构建操作更改为"Embedded Resource".

2.在文件"onComplete.js"中粘贴以下代码:

$('#input_apiKey').change(function () {

var key = $('#input_apiKey')[0].value;
if (key && key.trim() != "") {
key = "Bearer " + key;
window.authorizations.add("key", new ApiKeyAuthorization("Authorization",   key, "header"));
}
});
Run Code Online (Sandbox Code Playgroud)

3.打开文件"SwaggerConfig.cs"并在寄存器方法中粘贴下面的代码:

SwaggerUiConfig.Customize(c =>
{
 c.SupportHeaderParams = true;
 c.InjectJavaScript(typeof(SwaggerConfig).Assembly,        "AngularJSAuthentication.API.SwaggerExtensions.onComplete.js");
});
Run Code Online (Sandbox Code Playgroud)

小智 8

swagbuckles swagger的实现读取XML代码注释以生成所需的swagger规范.遗憾的是,如果您需要授权标头(访问令牌)来发出请求,则XML代码注释不会向Swashbuckle提供此信息.在swagger规范生成期间,您必须手动注入此新参数.

Swashbuckle提供了一个名为IOperationFilter的接口来应用新参数.实现此接口将如下所示.

public class AddAuthorizationHeaderParameterOperationFilter: IOperationFilter
{
    public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
    {
        var filterPipeline = apiDescription.ActionDescriptor.GetFilterPipeline();
        var isAuthorized = filterPipeline
                                         .Select(filterInfo => filterInfo.Instance)
                                         .Any(filter => filter is IAuthorizationFilter);

        var allowAnonymous = apiDescription.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();

        if (isAuthorized && !allowAnonymous)
        {
            operation.parameters.Add(new Parameter {
                name = "Authorization",
                @in = "header",
                description = "access token",
                required = true,
                type = "string"                    
            });
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在SwaggerConfig.cs文件中,添加以下内容

public class SwaggerConfig
{
    public static void Register()
    {
        var thisAssembly = typeof(SwaggerConfig).Assembly;

        GlobalConfiguration.Configuration
            .EnableSwagger(c =>


                c.SingleApiVersion("v1", "API").Description("An API ")
                                                        .TermsOfService("Some terms")
                                                        .Contact(cc => cc.Name("Team")
                                                        .Email("team@team.com"));

                c.OperationFilter(() => new AuthorizationHeaderParameterOperationFilter()));


      }
 }
Run Code Online (Sandbox Code Playgroud)

  • 但是,我想从UI(Swagger-UI)传递标题值.如何传递标题的值? (2认同)

Joh*_*ian 6

Swashbuckle建议使用InjectJavaScript来实现这一目标. https://github.com/domaindrivendev/Swashbuckle#injectjavascript

我使用以下代码在http标头中添加用于授权的承载令牌.

httpConfiguration
.EnableSwagger(c => c.SingleApiVersion("v1", "A title for your API")) co
.EnableSwaggerUi(c =>
    {
        c.InjectJavaScript(containingAssembly, "ProjectName.SwaggerUIEnableBearerToken.js");
    });
Run Code Online (Sandbox Code Playgroud)

SwaggerUIEnableBearerToken.js

$(function () {
$('#input_apiKey').attr("placeholder", "bearer token");
$('#input_apiKey').off();
$('#input_apiKey').change(function () {
    var token = this.value;
    if (token && token.trim() !== '') {
        token = 'Bearer ' + token;
        var apiKeyAuth = new window.SwaggerClient.ApiKeyAuthorization("Authorization", token, "header");
        window.swaggerUi.api.clientAuthorizations.add("token", apiKeyAuth);
        }
    }
});
})();
Run Code Online (Sandbox Code Playgroud)

从这个问题线程中查看更多内容:https: //github.com/domaindrivendev/Swashbuckle/issues/222

  • 这对我来说就像一个魅力. (2认同)