How do I handle JSONP with WebAPI? [duplicate]

一世执手 提交于 2019-11-30 22:04:53
EBarr

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!