Take the 2-minute tour ×

In my Web Api project I have a Get method which returns data from my datasource:

    [WebGet(UriTemplate = "")]
    public IQueryable<Product> Get()
        var products = _db.Products;
        return products.AsQueryable();

When I view this in the browser with the test client, when I specify to return as JSON it works fine and JSON is returned.

On my other client, I have to make a JSONP due to my API being hosted on same domain (For development only), but the data I receive back from my JSON request is XML, how can I make it return as JSON? Below is my code to make the request:

        crossDomain: true,
        dataType: "jsonp",
        url: "http://localhost:9000/api/products",
        type: "get",
        success: function (data) {

share|improve this question
It looks like you are still using the now obsolete WCF Web API rather than the newer ASP.NET Web API. See nuget.org/packages/AspNetWebApi –  Darrel Miller May 21 '12 at 23:51
@DarrelMiller - good catch. I didn't even notice the WebGet attribute. –  EBarr May 22 '12 at 12:37
I've since swapped it to use ASP.NET Web API and used EBarr's answer –  BiffBaffBoff May 22 '12 at 13:03
add comment

1 Answer

up vote 2 down vote accepted

Stealing liberally from this duplicate....

Your primary issue is that there is no JSONP media formatter registered in webapi by default.To accomplish what you want you need three things :

  1. to add a media formatter that outputs JSONP
  2. register the media formatter
  3. ensure the client requests jsonP.

You can steal this JSONP media formatter.

Then, you need to register the media formatter. You can do this programatically with the following code snippet:

var config = GlobalConfiguration.Configuration;
config.Formatters.Insert(0, new JsonpMediaTypeFormatter());

Generally you do this in Application_Start() in global.asax.

Your query looks like it's requesting JSONP just fine. Once the above is accomplished it should work. The important part is the accept header sent matches the accept header your shiny new jsonp formatter is listening for. The top two choices in my opinion are either: application/javascript (like you're requesting) or text/javascript.

share|improve this answer
add comment

Your Answer


