user467384
user467384

Reputation: 1167

MVC web api not working with getJSON on the same box, but returns valid JSON with 200 response when called

I have a simple MVC web api hosted on my local machine, all it does is return Personnel objects in JSON. On the same machine, I have a simple html page that is attempting to call that API using getJSON().

The getJSON call fails with the following error, despite the response returning successfuly, the server and client being the same machine, and the JSON being valid.

parsererror Error: jQuery110206749425150919706_1382127977754 was not called

In the controller...

// GET api/personnel
public List<Personnel> Get()
{
    return GetPersonnel();
}

GetPersonnel() just returns a list of Personnel objects

public class Personnel
{
    public String FirstName { get; set; }
    public String LastName { get; set; }
    public String RoomNumber { get; set; }
}

Added to Application_Start() to ensure only JSON is returned...

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter());

Here's the jQuery I'm using to call this API (on the same box).

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$.ajaxSetup({ async:false});
$(document).ready(function () {
    $("button").click(function () {
        var api = "http://localhost:13131/DirectoryServicePool/api/personnel?callback=?"; // this api doesn't work
        //api = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; // this api does
        $.getJSON(api, {
            format: "json"
        }, function (result) {
            alert("GotJSON");
        }).fail(function (XHR, status, error) {
            alert(status + ' ' + error);
        });
    });
});
</script>
</head>
<body><button>Get JSON data</button></body>
</html>

The response in fiddler (JSON is valid)...

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 18 Oct 2013 20:08:48 GMT
Content-Length: 244

[{"FirstName":"1","LastName":"5","RoomNumber":"6"},{"FirstName":"2","LastName":"5","RoomNumber":"6"},{"FirstName":"3","LastName":"5","RoomNumber":"6"},{"FirstName":"4","LastName":"5","RoomNumber":"6"}]

Thanks in advance.

Upvotes: 1

Views: 2791

Answers (1)

user467384
user467384

Reputation: 1167

Thank you for the comments, they helped point me in the right direction. I'm posting my solution in the hopes of saving other oblivious people time.

If your client is on a different site domain than your server you must use jsonp to get data using ajax, not json. It doesn't matter if they're on the same machine.

jQuery code

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
   $("button").click(function () {
    var api = "http://localhost:13131/DirectoryServicePool/api/personnel/";

    $.ajax({
        type: 'GET',
        url: api,
        success: function () {alert("it worked!");},
        dataType:'jsonp',
        contentType: "application/json"
        }); 
    });  
});
</script>
</head>
<body><button>Get JSON data</button></body>
</html>

Server side stuff

Install the JsonpMediaTypeFormatter in VS via Tools > Library Package Manager > Package Manager Tools

Install-Package WebApiContrib.Formatting.Jsonp

Add the following to your Application_Start() method in Global.asax.cs

GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter()));

Don't forget the using

using WebApiContrib.Formatting.Jsonp;

Upvotes: 2

Related Questions