How to create Header Parameters using Swashbuckle

There is a great sigh of relief when you find that tool to make your developer life easier for whatever you’re working on.  That happened recently when I found the Swashbuckle project.  In this post, I will show you a couple extensions for the Swashbuckle framework: Global Headers for all operations a [FromHeader] attribute for an individual operation.

Swashbuckle and SwaggerSwaggerUi

Swashbuckle will auto generate Swagger JSON specification from your Web API Controllers and Operations. 

The generated JSON will be inserted into the Swagger web interface. The beauty of the Swagger UI is that it lets you try each operation and generates the text boxes for each type of input, header, body, and parameters, etc. build the request, execute and display the results.  This is way easier than building a request in Fiddler, especially when the operation contract is changing frequently.  I have read somewhere that Swagger will become the standard for Web Api, but I can’t find that article, so it just remains speculation.

 

Global Header

The global header is useful when you want to apply a required header for each operation.  We used this for a Correlation Id to allow an easy way to string all logs together int he distributed environment.

 

  1. First you need to make sure Swashbuckle is installed and setup.  This is described here.

2. Create a Parameter class that implements IOperationFilter

 

3. Create a Parameter and apply in the Swashbuckle Configuration

 

Thats all there is to it, and you should now you will see the global header in each operation:

GlobalHeaderExample

 

Custom [FromHeader]

The From Header attribute idea came from here this StackOverFlow Article.  So you can follow that to create the Web Api header parameter attribute, I called my custom attribute, [FromHeader] to be consistent with the Web.Http attributes.

Then you need to provide a class that will find all the attributes and implement the IOperationFilter interface.

 

Finally apply the class above to the Swashbuckle configuration setup:

 

and you have an easy way to add header values to each Rest operation.  I personally find the global header more useful, but I wanted to find a way to do this using Swashbuckle.

 

Hopefully that brings another little sigh of relief to your day.

4 thoughts on “How to create Header Parameters using Swashbuckle

Leave a Reply

Your email address will not be published. Required fields are marked *