Web API Versioning Using Custom Media Types
In this article, I am going to discuss Web API Versioning Using Custom Media Types i.e. Vendor Specific Media Types 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 Accept Header.
So what we want to do here is, instead of using the built-in media types such as application/json or application/xml, we want to use our custom media type which is shown in the below postman request.
Notice that in the media type, we have specified the version of the service that we want. The custom media types are prefixed with vnd which indicates that this media type is a vendor specific media type.
So what we need to do from our CustomControllerSelector class is to read the version number from the custom media type that we have specified in the request.
Modify the CustomControllerSelector class as shown below where we implement the logic to read the version number from the custom media type. The code is self-explanatory, so please go through the lines.
That’s it; we are done with our implementation. Build the solution and issue a request without using the custom media type from the postman. You will get version 1 of employee objects in JSON format as shown below.
Now specify the custom media type and set the version as 2 and issue a request, then you will get the version 2 of the employee objects as expected as shown in the below image.
That’s work as expected. But there is a problem. The problem is if you specify that you want the data in XML format instead of JSON format in the request as shown below, then you will get the data in JSON format instead of the XML format.
The reason is, we have not added our custom Media Type to the respective media type formatters i.e. JsonFormatter and XmlFormatter.
Adding Custom Media Types:
Include the following two lines of code within the WebApiConfig.cs file to add our custom media types to the JsonFormatter
Similarly, include the following two lines of code within the WebApiConfig.cs file to add the custom media types to the XmlFormatter
So at this point, the complete code of the WebApiConfig.cs is given below.
So now build the solution and issue a request by specifying that you want the data in XML format and you will get the data as expected as shown below.
In this article, I try to explain how to implement Web API Versioning Using Custom Media Types 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.
No HTML was returned.