1

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:

    $.ajax({
        crossDomain: true,
        dataType: "jsonp",
        url: "http://localhost:9000/api/products",
        contentType: 'application/json; charset=utf-8',
        type: "get",
        success: function (data) {

            console.log(data);
        }
    });
CallumVass
  • 11,288
  • 26
  • 84
  • 154

1 Answers1

2

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.

Community
  • 1
  • 1
EBarr
  • 11,826
  • 7
  • 63
  • 85