Web API Versioning Using Accept Header
In this article, I am going to discuss Web API Versioning Using Accept Header with an example. This is a continuation part of our previous article, so please read our previous article before proceeding to this article where we discussed Web API Versioning Using Custom Header.
What is Accept Header?
The Accept header tells the server in which file format the browser wants the data. These file formats are generally called as MIME-types. The MIME stands for Multipurpose Internet Mail Extensions.
In the Content Negotiation in Web API article, we discussed that, if we want the Web API service to return data in XML format then we need to set the Accept header value to application/xml. Similarly, if we want the Web API service to return the data in JSON format then we need to set the Accept header value to application/json.
Implementing Web API Versioning using accept header
In our last article, we discussed how to create a custom header for versioning. Si, instead of creating a custom header, which is used only for versioning purpose, we can make use of the built-in Accept header. Within the Accept header, we can add additional parameters to send the additional data along with the request to the server. For example, we can specify the version of the service that we want by using the version parameter as shown in the below image.
What we need to do here is, now we need to read the Version parameter value from the Accept header in our CustomControllerSelector class. So modify the CustomControllerSelector class as shown below. The code is self-explained, so please read the comments.
That’s it; we have done with our implementation. Run the application and then issue a request without the Accept header using the postman as the client, the service falls back to version 1 and returns version 1 employee objects in JSON format as expected as shown in the below image.
Now, specify the version parameter as part of the Accept header then you will get the response in the specified version as expected as shown in the below image.
In the next article, I will discuss how to implement the Web API versioning using Custom Media Types with an example.
In this article, I try to explain how to implement Web API Versioning Using Accept Header step by step with an example. I hope this article will help you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.