JSONP request to your WebAPI service

A day ago, I was trying to prepare a demo on how simple it is to make a cross domain AJAX request to a web service, and display the JSON result in a friendly HTML div using jQuery AJAX method.

I created a simple WebAPI controller, which had a method which returns a IEnumerable<MyObject> of a list of objects, and published it to a Windows Azure Cloud Service. The Web Service was working like a charm.

When I created the jQuery code, which was as simple as this

$(function () {
var url = "http://webprogramming.cloudapp.net/api/Kompanite?callback=?"

$.getJSON(url, function (data) {
$.each(data, function (index) {
//place info in a div
});
});
});

and was supposed to work smoothly. But, as opposed to a working code, I started to receive no results. I started to catch ajax errors, and saw that the callback function was not being called. After three hours of research, I came through this “JSONP with ASP.NET WebAPI” StackOverflow question, which explained everything. The answer was that, by default, the result of WebAPI was not prepared to deal with callback required for JSONP. You need to have a special¬†JsonMediaTypeFormatter which can handle this kind of situation. After I copied/pasted the formatter class from the answer, and cofigured it in Global.asax’s Application_Start() method through this line:

config.Formatters.Insert(0, new JsonpMediaTypeFormatter());

the jQuery code started to work like a charm. So… if you fall into a similar situation, please make sure you implement your own JsonMediaTypeFormatter to support JSONP calls to your web service.