带有 ASP.NET Web API 的 JSONP [英] JSONP with ASP.NET Web API

查看:30
本文介绍了带有 ASP.NET Web API 的 JSONP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Web API 在 ASP.MVC MVC 4 中创建一组新服务.到目前为止,它很棒.我已经创建了服务并让它开始工作,现在我正在尝试使用 JQuery 来使用它.我可以使用 Fiddler 取回 JSON 字符串,这似乎没问题,但由于该服务存在于单独的站点上,因此尝试使用带有不允许"的 JQuery 错误调用它.所以,这显然是我需要使用 JSONP 的情况.

I am working on creating a new set of services in ASP.MVC MVC 4 using the Web API. So far, it's great. I have created the service and gotten it to work, and now I am trying to consume it using JQuery. I can get back the JSON string using Fiddler, and it seems to be ok, but because the service exists on a separate site, trying to call it with JQuery errors with the "Not Allowed". So, this is clearly a case where I need to use JSONP.

我知道 Web API 是新的,但我希望有人能帮助我.

I know that the Web API is new, but I'm hoping someone out there can help me.

如何使用 JSONP 调用 Web API 方法?

How do I make a call to a Web API method using JSONP?

推荐答案

问完这个问题,终于找到了自己需要的东西,所以来回答一下.

After asking this question, I finally found what I needed, so I am answering it.

我遇到了这个 JsonpMediaTypeFormatter.通过执行以下操作将其添加到 global.asax 的 Application_Start 中:

I ran across this JsonpMediaTypeFormatter. Add it into the Application_Start of your global.asax by doing this:

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

您可以使用如下所示的 JQuery AJAX 调用:

and you are good to go with an JQuery AJAX call that looks like this:

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

看起来效果很好.

这篇关于带有 ASP.NET Web API 的 JSONP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆