In this blog, we are
going to discuss how to add custom header parameter (authorization header) in
Swagger UI for ASP.Net web API.
We use request header
(like authentication) to pass client information to web API but in Swagger UI,
there is no any simple or straight way to add custom header parameter.
To add customer
header parameter in Swagger UI, we need to implement IOperationFilter interface
internal class AuthorizationHeaderParameterOperationFilter : IOperationFilter
{
public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription)
{
if (operation.parameters
== null)
operation.parameters
= new List<Parameter>();
operation.parameters.Add(new Parameter
{
name
= "X-API-Token",
@in
= "header",
description
= "access token",
required
= true,
type
= "string"
});
}
}
SwaggerConfig .cs :
public static void Register()
{
var thisAssembly
= typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c
=>
{
c.SingleApiVersion("v1", "DemoWebAPI");
c.OperationFilter<AuthorizationHeaderParameterOperationFilter>();
})
.EnableSwaggerUi(c
=> { });
}
As below you can see, X-API-token as additional parameter for your Web API to take authorization token and pass to web API for user authentication
Other swagger related posts:
Thanks for visiting!!
2 comments:
Is there any way to do this without displaying header input fields in the UI?
I am having a great deal of trouble finding a way to add custom header fields with static, preset values to all swagger API calls, without displaying the fields and their values in the UI.
I tried this. The customer header comes under Results View of httpContext.Request.Headers resultset but when I do var key = httpContext.Request.Headers.Where(z => z.Key == "CUSTOMKEY").FirstOrDefault(); I get key as [null,null]. Any ideas?
Post a Comment