ASP.NET Web API: How content negotiation works?

One cool new feature that ASP.NET Web API introduces is support for content negotiation. Content negotiation is mechanism that allows web server to serve content in different format using same URL. In this posting I will show you how to use ASP.NET Web API to serve content in JSON and XML formats.

How content negotiation works

Content negotiation takes place when browser or some other HTTP-client tells server what content formats it accepts. HTTP-client uses Accept header to list all formats it can read. Accept: */* means that client is okay with every content format that server is able to provide. By example, one HTTP-client may accept content in JSON and the other in XML.

Two possible things can happen as a result of negotiation. Client and server agree with format or they don’t. In latter case server gives content out in its default format and it is up to client to get something done with this answer (log an error, by example).

Web API and content negotiation

In this posting we will focus on basic content negotiation support offered by ASP.NET Web API. I will show you how to extend Web API content negotiation in later postings. First we take a look how things work out-of-box and then we try to make things work like we want. We will play with built-in features in this posting.

Let’s suppose we have simple database with contact data and we want to use this database from some other system or from some browser-based AJAX-application. On contact data form I have button that helps me making AJAX-requests to Web API.

Content negotiation testing application

Here is the code behind Get Data button:

$.ajax({
    type:
'GET'
,
    url:
"api/contacts/"
});

This code just asks data from Web API and returns some data. When we click the button we get the following response:

Default request to Web API

Default response from Web API

Now let’s change the code behind button and let’s specify that we want data back in XML:

$.ajax({
    beforeSend:
function
(req) {
        req.setRequestHeader(
"Accept", "text/xml"
);
    },
    type:
'GET'
,
    url:
"api/contacts/"
});

Browser sends now Accept header with value text/xml. The answer from server is here:

Request to Web API and we ask for XML response

Response to XML request

Okay, we got data in JSON and XML and both of these formats are widely accepted by tools on different platforms.

What if client and server doesn’t agree?

Now let’s try out what happens when we ask something that Web API doesn’t support out-of-box. Perfect fit for contacts should be vCard:

$.ajax({
    beforeSend:
function
(req) {
        req.setRequestHeader(
"Accept", "text/x-vcard"
);
    },
    type:
'GET'
,
    url:
"api/contacts/"
});

The result is here:

Default response to Web API

Default response from Web API

What we got is same JSON we saw in our first experiment. Web API was not able to convert response to vCard and instead of failing or throwing nasty exceptions it gave us our default answer – JSON.

Conclusion

Built-in content negotiation helps us server same content in different formats to different clients. Clients have to say what format they expect and as long as Web API is able to convert results to this format the client gets content in format it asked it. Providing more than one content format with our API is only good – it makes other developers way easier to use our API with tools they have and this way our API finds more serious users easily.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    10 thoughts on “ASP.NET Web API: How content negotiation works?

    • April 19, 2012 at 5:30 pm
      Permalink

      Will you be going into how the structure of the data coming out of Web API impacts Content Negotiation?

    • April 20, 2012 at 6:00 am
      Permalink

      Thanks for feedback, guys! :)

      Jesse, I have some more posts about content negotiation coming. Stay tuned! One of these will show how to extend Web API with formats not supported ouf-of-box.

    • April 20, 2012 at 10:32 am
      Permalink

      “In latter case server gives content out in its default format and it is up to client to get something done with this answer” – do you know if there’s a way to prevent this? Because I’d *like* to return a 406 – you know, the error code that specifically exists if the client and server cannot agree on a content type.

    • April 20, 2012 at 11:56 am
      Permalink

      Thanks for question, Damien. I’m not sure right now how to achieve this functionality. I will try to find solution and if I find something I will blog about it.

    • May 6, 2012 at 4:04 pm
      Permalink

      Hi Gunnar,

      I’ve added jsonp formatter to my GlobalConfiguration
      GlobalConfiguration.Configuration.Formatters.Add(new JsonpMediaTypeFormatter());

      Then i try to call my webapi using format that’s not supported..that means it should return json:
      $.ajax({
      url: “/api/courses”,
      dataType: “x-vcard”,
      type: “GET”,
      success: function (data) {
      var list = $(‘#courses’);
      for (var i = 0; i < data.length; i++) { var course = data[i]; list.append('' + course.name + ''); } }, statusCode: { 401: function () { alert('Login please'); }, 200: function (jqXHR, textStatus, errorThrown) { alert('succcess'); } }, error: function (jqXHR, textStatus, errorThrown) { alert('error'); alert(jqXHR.statusText + " ----- " + jqXHR.responseText); } }); Here's request/response from fiddler: GET http://localhost:64009/api/courses HTTP/1.1
      Host: localhost:64009
      User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0
      Accept: */*
      Accept-Language: en-us,en;q=0.5
      Accept-Encoding: gzip, deflate
      Connection: keep-alive
      X-Requested-With: XMLHttpRequest
      Referer: http://localhost:64009/home/courses

      HTTP/1.1 200 OK
      Server: ASP.NET Development Server/10.0.0.0
      Date: Sun, 06 May 2012 16:01:07 GMT
      X-AspNet-Version: 4.0.30319
      Transfer-Encoding: chunked
      Cache-Control: no-cache
      Pragma: no-cache
      Expires: -1
      Content-Type: application/json
      Connection: Close

      49
      [{“id”:0,”name”:”.net”},{“id”:1,”name”:”oData”},{“id”:2,”name”:”WebApi”}]
      0

      And it returns json, but my ajax callback goes to error and shows the following message:
      parseerror – [{“id”:0,”name”:”.net”},{“id”:1,”name”:”oData”},{“id”:2,”name”:”WebApi”}]

      why it’s not calling success callback function?

    • May 29, 2012 at 3:03 pm
      Permalink

      It’s beause dataType: “x-vcard” says what parser jQuery should use to parse the response. It does not affect Accept header in any way.

    • June 29, 2012 at 8:15 am
      Permalink

      I like your reviews about asp .net. That are most interesting and very useful for me. I can take some ideas form this post for Asp .Net Development. Thanks for share this valuable Info.

    • Pingback:ASP.NET Web API: Extending content negotiation with new formats | Gunnar Peipman - Programming Blog

    • Pingback:Consuming ASP.NET Web API services from PHP script | Gunnar Peipman - Programming Blog

    • November 19, 2014 at 2:54 pm
      Permalink

      we understood all the things but unable to understand about the flow of calling method from Web Application. like on which method it will hit first in API. please tell about flow too.

    Leave a Reply

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