X

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.

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:

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:

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:

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.

Liked this post? Empower your friends by sharing it!
Categories: ASP.NET

View Comments (356)

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

  • 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.

  • "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.

  • 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.

  • 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?

  • 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.

  • 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.

  • 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.

  • When someone writes an article he/she keeps the thought of a user in his/her mind that how a user can know it.
    Therefore that's why this piece of writing is great.
    Thanks!

  • I visited many web pages except the audio quality for audio songs present at this site is truly wonderful.

  • You're so awesome! I don't believe I've read a single thing like that before.
    So nice to find someone with a few unique thoughts on this issue.
    Really.. thank you for starting this up. This web site is one thing that's needed on the internet,
    someone with a little originality!

  • Hello, i think that i saw you visited my weblog thus i got here
    to go back the desire?.I am attempting to to find things to improve
    my website!I guess its ok to make use of some of your ideas!!

  • Hi there! I just wanted to ask if you ever have any trouble
    with hackers? My last blog (wordpress) was hacked and I ended up losing many months of hard work due
    to no backup. Do you have any solutions to stop hackers?

  • I am not sure where you are getting your info, but good topic.

    I needs to spend some time learning much more or understanding more.
    Thanks for fantastic info I was looking for this info
    for my mission.

  • I was curious if you ever thought of changing the page layout of your site?

    Its very well written; I love what youve got to say. But maybe you could a little more
    in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having 1 or 2 images.
    Maybe you could space it out better?

  • Do you have a spam issue on this blog; I also am a blogger, and I
    was curious about your situation; many of us have created some nice procedures and we are looking to exchange strategies with other folks,
    why not shoot me an email if interested.

  • It is really a nice and helpful piece of information.
    I am glad that you shared this useful info with us. Please stay us up
    to date like this. Thank you for sharing.

  • I read this article completely about the resemblance of most up-to-date
    and previous technologies, it's amazing article.

  • It is appropriate time to make some plans for the longer term and it's time to be happy.
    I've learn this post and if I may just I wish to suggest you few attention-grabbing
    things or tips. Perhaps you can write subsequent articles regarding
    this article. I desire to learn more things about it!

  • Lodibet app - ƅеst slot online in tһe Philippines
    better tһɑn jilibet аnd pg slot
    free Spins 3000+ Free Demo Slot

    searching Lodibet օn Google օr Bing to get free coins
    for play

    lodibet app

  • Hey there! Quick question that's completely off topic. Do you
    know how to make your site mobile friendly?
    My website looks weird when browsing from my apple iphone.

    I'm trying to find a theme or plugin that might be able
    to fix this problem. If you have any suggestions, please share.
    With thanks!

  • It's amazing to pay a quick visit this site and reading the views of all mates about this
    post, while I am also eager of getting familiarity.

  • Hawkplay vip - Υou can Uѕe GCash to play іn anytime
    Free Spins 1000+ Free Demo Slot
    Openning Bonus 120% piso ƅack
    Searching hawkplay casino on Google օr Bing to get free coins

    hawkplay vip

  • My brother suggested I might like this website.
    He was totally right. This post truly made my day. You cann't imagine simply how much time I had spent for this info!
    Thanks!

  • After going over a handful of the blog posts on your web page, I seriously appreciate
    your way of blogging. I saved as a favorite it to my bookmark website
    list and will be checking back in the near future. Please visit my web site too and tell me how you feel.

  • Hello to every body, it's my first go to see of this webpage;
    this weblog includes remarkable and in fact good data designed for readers.

  • It's an remarkable paragraph in support of all the web
    viewers; they will take advantage from it I am sure.

  • I know this if off topic but I'm looking into starting my own blog and was wondering what all is required to get setup?

    I'm assuming having a blog like yours would cost a pretty penny?

    I'm not very web smart so I'm not 100% certain. Any recommendations or advice would be greatly appreciated.
    Kudos

  • Lawinplay - You ϲan Uѕe GCash to play іn anytime
    Free Spins 1000+ Free Demo Slot
    Openning Bonus 120% piso ƅack
    Searching lawinplayvip.net on Google οr Bing to get free coins

    lawinplay

  • PP Gaming - bеѕt slot online in tһe Philippines
    better than jili slot and pg slot
    free Spins 3000+ Free Demo Slot

    searching ppgaming.օrg on Google or Bing to ɡet free coins fߋr play

    pp gaming

  • I was recommended this website by my cousin. I am not sure whether this post
    is written by him as nobody else know such detailed about my difficulty.

    You're incredible! Thanks!

  • When I originally commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get three
    e-mails with the same comment. Is there any way you can remove people from that service?
    Thank you!

  • Spot on with this write-up, I honestly feel this site needs a great
    deal more attention. I'll probably be returning to read more, thanks for the info!

  • When some one searches for his essential thing, so he/she needs to
    be available that in detail, thus that thing is maintained over here.

  • Lodibet - beѕt slot online in tһe Philippines
    betteг than jilibet аnd pg slot
    free Spins 3000+ Free Demo Slot

    searching Lodibet ᧐n Google ߋr Bing to get free coins for play

    lodibet.com

  • YGR slot เป็นหนึ่งในผู้นำเสนอเกมสล็อตออนไลน์ที่ได้รับความนิยมอย่างมากในประเทศไทย ด้วยมาตรฐานของเกมและการดูแลที่ยอดเยี่ยม YGR slot จึงจูงใจนักพนันออนไลน์จำนวนมากให้เข้ามาเล่นเกมสล็อตที่หลากหลาย

  • Hi to every one, it's in fact a fastidious for me to pay a quick visit this site,
    it contains useful Information.

  • Excellent beat ! I wish to apprentice whilst you amend your website, how could i subscribe
    for a blog web site? The account helped me a appropriate deal.
    I had been a little bit familiar of this your broadcast provided vibrant clear concept

  • Write more, thats all I have to say. Literally,
    it seems as though you relied on the video to make your point.

    You clearly know what youre talking about, why waste your intelligence on just posting videos to your site when you could be giving us something enlightening to read?

  • whoah this blog is excellent i like reading your posts.

    Keep up the great work! You understand, a lot of persons are looking
    around for this info, you can help them greatly.

  • Pretty! This has been an extremely wonderful article.
    Many thanks for providing these details.

  • Right away I am going to do my breakfast, later than having my breakfast coming over again to read other news.

  • Do you have a spam issue on this website; I also am
    a blogger, and I was wanting to know your situation; we have developed some nice procedures and we
    are looking to swap strategies with other folks, be sure to shoot me an email if interested.

  • Hello! Do you know if they make any plugins to assist with Search Engine Optimization? I'm
    trying to get my blog to rank for some targeted keywords but I'm not seeing very good success.

    If you know of any please share. Thank you!

  • Emiratefix
    UAE Duabi
    0543747022

    تصليح غسالات سيمنس, تصليح غسالات سيمنز 0543747022

    تصليح غسالات سيمنس - jobs251.com -

  • I don't know if it's just me or if perhaps everyone else
    encountering issues with your site. It appears
    as though some of the written text in your content are
    running off the screen. Can someone else please provide feedback and let
    me know if this is happening to them too? This
    might be a issue with my web browser because
    I've had this happen previously. Appreciate it

  • My programmer is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the expenses.

    But he's tryiong none the less. I've been using WordPress on a number of websites for about
    a year and am concerned about switching to another platform.
    I have heard good things about blogengine.net. Is there a way I can transfer
    all my wordpress content into it? Any help would be greatly appreciated!

  • Hawkplay vip - Үοu ⅽan Use GCash to play in anytime
    Free Spins 1000+ Free Demo Slot
    Openning Bonus 120% piso ƅack
    Searching hawkplay casino ߋn Google oг Bing to gеt free coins

    hawkplay vip login

  • Your style is very unique compared to other folks I have read stuff from.
    Thank you for posting when you have the opportunity, Guess I'll just book mark this page.

  • Quality posts is the important to interest the visitors to
    pay a visit the website, that's what this website is providing.

  • I love reading an article that will make men and
    women think. Also, thank you for permitting me to comment!

  • Hi there, I discovered your web site via Google while looking
    for a comparable subject, your web site came up, it appears good.
    I have bookmarked it in my google bookmarks.
    Hello there, simply changed into alert to your blog through Google, and located
    that it's truly informative. I am gonna watch out for brussels.
    I'll be grateful in case you proceed this in future. A lot of other folks will probably
    be benefited out of your writing. Cheers!

  • I’m not that much of a online reader to be honest but your sites really nice, keep it up!
    I'll go ahead and bookmark your site to come back later on. Many
    thanks

    Have a look at my web-site ... ruay รวย

  • Lawinplay - Yoᥙ can Use GCash to play in anytime
    Free Spins 1000+ Free Demo Slot
    Openning Bonus 120% piso ƅack
    Searching lawinplayvip.net οn Google оr Bing to get free coins

    lawinplay

  • Write more, thats all I have to say. Literally, it seems
    as though you relied on the video to make your point. You obviously know what youre
    talking about, why throw away your intelligence on just posting videos to
    your weblog when you could be giving us something enlightening to read?

  • Quality posts is the main to attract the visitors to pay a quick visit the web page,
    that's what this web site is providing.

  • I like the valuable information you provide in your articles.
    I will bookmark your blog and check again here regularly. I'm quite sure I will
    learn many new stuff right here! Best of luck for the next!

  • I thought this post is timely and relevant. Thank you
    exceedingly for creating this article; if more people wrote
    time-worthy and intelligent prose, I gander we'd all be in a better situation. To me, I know might place our attention more on eating well
    and keeping fit and alive and free from being always in front of the
    computer or cell phone screen. Go outside!!
    (and not being glued to the cell phone all the while, either) and living
    a life with appreciation for the natural world, keeps people feeling grounded.
    Considering important topics is likewise some other sort of experience that can aid us know ourselves.

  • When someone writes an post he/she maintains the thought
    of a user in his/her brain that how a user can understand it.
    Therefore that's why this post is perfect. Thanks!

  • It's awesome to pay a visit this web page and reading the views of all colleagues regarding this article,
    while I am also eager of getting familiarity.

  • І always սsed to study post in news papeгs but now as I am a user
    of internet thus from now І am using net for posts, thаnks to wеb.

    Feel free to visit my wеbpage :: factory uniform

  • I pay a visit every day some web sites and information sites to read
    articles, but this web site gives quality based writing.

  • PPGaming register - ƅеst slot online іn the Philippines
    Ьetter thаn jili slot and pg slot
    free Spins 3000+ Free Demo Slot

    searching ppgaming.οrg on Google or Bing to get free coins for play

    ppgaming register

  • Aw, this was an incredibly nice post. Taking a few minutes and actual effort to produce a top notch article… but what can I say… I hesitate a whole lot and never manage to
    get nearly anything done.

  • Thank you for some other informative blog. The place
    else could I get that kind of info written in such a perfect means?
    I have a venture that I am just now running on, and I have been at the glance out for
    such info.

  • Hi, I think your site might be having browser compatibility issues.

    When I look at your website in Firefox, it looks fine but
    when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up! Other
    then that, excellent blog!

  • ۱۹۶۳-۱۹۶۷: لیسانساش را در رشته ریاضیات از
    کالج اوبرلین گرفت. تسلا در ابتدا قصد داشت از تعویض گسترده باتری پشتیبانی کند، اما ظاهراً به دلیل عدم علاقه مشتریان، این طرح را رها
    کرد. اما کی معتقد بود که ایدههای خارج
    از علوم کامپیوتر برای پیشرفت این رشته حایز اهمیت هستند.
    باز هم، اسمیت و تیمش نمونه اولیه
    محصول را ساختند اما قبل از
    اینکه آن را بهصورت کامل اجرا کنند، Dest با مشکلات مالی مواجه شد.
    ۱۹۸۵-۱۹۸۸: یکی از مؤسسین و معاون رابطهای انسانی در Cognition - این یک استارت آپ در ماساچوست بود که میخواستند آنچه
    را ایستگاههای کاری مانند Mentor Graphics از Daisy برای مهندسان برق انجام داد، آنها به مهندسان مکانیک انجام دهند.
    در نتیجه، او نمونه اولیه یک اپلیکیشن جدید را
    که برای دیتابیسهای منطقی مورد کاربرد داشت را ساخت، کاری که VisiCalc با مدلسازی
    مالی میکرد. او یک نماد (آیکن) مذهبی را دید و
    اجسامی را ترسیم میکرد که بهصورت
    مشابه معنای دوگانه دارند، بنابراین نام این اجسام را آیکن گذاشت.

  • Hello my loved one! I want to say that this post is awesome, nice written and come
    with approximately all important infos. I would like
    to see extra posts like this .

  • When soke one sеaгches for hiss vital thing, thus һe/she desires to be availaƅle thɑt in detail, therefore
    thhat thing іѕ maintained over here.

    Feel free to visit my wеb site: slope unbkocked

  • I quite like reading through a post that will make men and women think.
    Also, thank you for allowing me to comment!

  • I'm truly enjoying the design and layout of your website.
    It's a very easy on the eyes which makes it much more
    pleasant for me to come here and visit more often.
    Did you hire out a designer to create your theme?
    Outstanding work!

  • Hey there suрerb blog! Does running a blog like thgіs
    require a massive amount work? I've aabsolutely noo exрertise inn computer programming
    but I was hoping to start my oown blog in the near
    future. Anyhow, іf you have any recommendations or techniqyes for
    new blog owners please share. I understand this is
    оoff subјect ƅut I simply needed to ask. Cheers!

    Feel freе to surf too my blog post bouncy balls

  • jili slot demo - Ьеst slot online іn tһe Philippines
    Ƅetter thаn fachai slot аnd pg slot
    free Spins 3000+ Free Demo Slot

    searching jilislot365 οn Google ᧐r Bing to get free
    coins for play

    jili slot demo

  • Hi, i feel that i noticed you visited my weblog so i got here to go back the desire?.I am attempting to to find things
    to improve my site!I suppose its adequate to make use of some of your concepts!!

  • Hi there! I'm at work surfing around your blog from my new iphone 3gs!
    Just wanted to say I love reading through your
    blog and look forward to all your posts! Keep up the superb work!

  • Hi there, I enjoy reading through your article. I like to write a little comment to support you.

  • Pretty! This has been an extremely wonderful post.

    Thank you for providing this info.

  • An impressive share! I've just forwarded this
    onto a friend who was conducting a little research on this.
    And he actually ordered me lunch due to the fact that I
    found it for him... lol. So let me reword this.... Thank
    YOU for the meal!! But yeah, thanx for spending some time to talk
    about this issue here on your web page.

  • Wow that was strange. I just wrote an extremely
    long comment but after I clicked submit my comment didn't appear.
    Grrrr... well I'm not writing all that over again. Regardless, just wanted to
    say excellent blog!

  • Ванкер Жесткая задница बदमाश 婊子
    荡妇 कुतिया, कृपया Лахзахои чеҳра

  • Hi there! I simply would like to offer you a big thumbs up for your great info you have here on this post.
    I will be coming back to your blog for more soon.

  • Hi, its good paragraph concerning media print, we all
    understand media is a fantastic source of data.

Related Post