One of our REST API’s always requires an ‘X-API-Key’ header. To simplify testing, I wanted to have the option to specify the header in the Swagger UI.
Let’s see how we can get this done through SwashBuckle.
First I need to create a custom IOperationFilter that will add the header:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using Microsoft.OpenApi.Models; | |
using Swashbuckle.AspNetCore.SwaggerGen; | |
public class AddHeaderParameter : IOperationFilter | |
{ | |
public void Apply(OpenApiOperation operation, OperationFilterContext context) | |
{ | |
if (operation.Parameters == null) | |
operation.Parameters = new List<OpenApiParameter>(); | |
operation.Parameters.Add(new OpenApiParameter | |
{ | |
Name = "X-Api-Key", | |
In = ParameterLocation.Header, | |
Required = true, | |
Schema = new OpenApiSchema | |
{ | |
Type = "string" | |
} | |
}); | |
} | |
} |
Now we need to update our Swagger configuration to use this header:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Register the Swagger generator, defining 1 or more Swagger documents | |
services.AddSwaggerGen(c => | |
{ | |
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Example API", Version = "v1" }); | |
c.OperationFilter<AddHeaderParameter>(); | |
}); |
If we now run our application and browse to the Swagger UI, we should see the extra header parameter: