How do I handle JSONP with WebAPI?

phoenix picture phoenix · May 9, 2012 · Viewed 7.1k times · Source

Possible Duplicate:
JSONP with MVC 4 WebApi

I have a get method for my WebAPI which is as follows:

    private T Get<T>(string uri)
    {
        T result = default(T);
        bool isSuccess = true;

        client
            .GetAsync(uri)
            .ContinueWith(task =>
            {
                // EnsureStatus
                isSuccess = task.Result.IsSuccessStatusCode;
                task
                .Result
                .Content
                .ReadAsAsync<T>()
                .ContinueWith(t => result = t.Result)
                .Wait();
            })
            .Wait();
       return result;
     }

The result is produced in a JSON format but I want it for JSONP.

I have read that ReadAsSync only handles built in mediaformatters. So is there a way I can change it to handle JsonP?

Answer

EBarr picture EBarr · May 9, 2012

Stealing liberally from this duplicate....

To accomplish what you want you need three things :

  1. to add a media formatter that outputs JSONP
  2. register the media formatter (traditionally done through global.asx)
  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());

Since you apparently don't use global.asax you're going to need to make sure the formatter is registered somehow. YOU don't provide enough information on how to do it, but i suspect a judiciously placed IF statement and a static variable indicating registration would get you there.

I still don't quite know what type of client you're using, but if it's jquery something like the following will get you there:

$.ajax({
    url: 'http://myurl.com',
    type: 'GET',
    dataType: 'jsonp',
    success: function (data) {
        alert(data.MyProperty);
    }
})

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 or text/javascript.