Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

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.

ASP.NET Web API test 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:

Content negotiation: Response type is application/json

Content negotiation: JSON response

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:

Content negotiation: Response is XML

Content negotiation: Response data as XML

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:

Content negotiation: Response type is application/json

Content negotiation: JSON response

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.

Posted: Apr 19 2012, 12:12 PM by DigiMortal | with 11 comment(s)
Filed under:

Comments

Jesse Williamson said:

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

# April 19, 2012 1:30 PM

DigiMortal said:

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 2:00 AM

Damien said:

"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 6:32 AM

DigiMortal said:

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.

# April 20, 2012 7:56 AM

SCV said:

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('<li>' + course.name + '</li>');

           }

       },

       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 localhost/.../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: localhost/.../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 6, 2012 12:04 PM

kpomka said:

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.

# May 29, 2012 11:03 AM

Charles Terry said:

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.

# June 29, 2012 4:15 AM