This project is read-only.

JSONP Sample and executing real world version

Topics: jQuery, Web Api
Nov 30, 2011 at 2:59 PM

I was trying to use the OOTB JSONP support and got the sample up and running no problem. I noticed that it wasn't really crossing domains. The sample used a url like 'hello/' which works because its running in the same domain, JQuery puts the AcceptHeader of "application/javascript" This seems to work just fine because the JSONP formatted is looking for 'application/javascript'

Then I created my own sample using two different sites so that the domain would be different.  In my example where I use a full url like 'http://localhost:9999/horse' JQuery does put the proper items on the query string but uses an accept header of */* .  The service does work, but returns XML.

At first I removed System.Net.Http.Formatting.XmlMediaTypeFormatter and System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter from the formatters and this worked with the following header

Here is my header

GET http://localhost:1491/horse?callback=jQuery17103727521630935371_1322663839962&_=1322664574594 HTTP/1.1
Host: localhost:1491
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2
Accept: */*Referer: http://localhost:35451/DEFAULT.htm
Accept-Encoding: gzip,deflate,sdchAccept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.35451/DEFAULT

I tried everything I could think of when making the $.ajax call to change the Accept and all of them resulted in an accept header of */*

Finally, I moved XmlMediaTypeFormatter and FormUrlEncodedMediaTypeFormatter to the third and fourth position in teh Formatters collection and teh JSONP continuted to work.

      config.Formatters.Add(new System.Net.Http.Formatting.XmlMediaTypeFormatter());
      config.Formatters.Add(new System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter());

 Hope this helps someone

Nov 30, 2011 at 6:38 PM

You are correct that in general the browser will not actually send a useful accept header for JSONP requests. Instead what you generally need to do is put something in the URI that indicates to the Web API that you want JSONP. There are a bunch of conventions for doing this, but no clear standard. So, we added a UriPathExtensionMapping to the JsonpMediaTypeFormatter that maps .jsonp to the application/javascript media type. The sample isn’t currently issuing the request this way, but I updated it to do so.

$.getJSON("/api/hello.jsonp?callback=?", function (data) {



The one gotcha with this approach is that when you use UriPathExtensionMappings you need to account for the extention in your URI template. I have updated the sample to do this as well:


public string GetHelloWorld()


return "Hello, World!";


Daniel Roth