Example of content negotiation and basic authentication in Web API MVC

click here to get full sample project 

CONTENT NEGOTIATION and basic AUTHENTICATION IN WEB API

One of the features of the RESTful service is that, the client has the ability to decide in which format they want the response - XML, JSON etc. A request that is sent to the server includes an Accept header. Using the Accept header the client can specify the format for the response. For example

Accept: application/xml returns XML

Accept: application/json returns JSON

Depending on the Accept header value in the request, the server sends the response. This is called Content Negotiation.

So what happens client request for data in a specific format
The Web API controller generates the data that we want to send to the client. For example, if you have asked for list of User Expense. The controller generates the list of User Expense, and hands the data to the Web API pipeline which then looks at the Accept header and depending on the format that the client has requested, Web API will choose the appropriate formatter. For example, if the client has requested for XML data, Web API uses XML formatter. If the client has requested for JSON data, Web API uses JSON formatter. These formatters are called Media type formatters.

ASP.NET Web API is greatly extensible i.e. we can also plugin our own formatters, for custom formatting the data.

 

Let us see how the request is sending to the Web Api  and get the data in JSON format:  Please download the Fidler from the below link : https://www.telerik.com/download/fiddler/fiddler4

 

Then click on the execute button:

Now Get data in the XML format: First make the request in header as content-type to application/XML

 

Below is the data return after executing above request which is in XML: