JSONP用的ASP.NET Web API [英] JSONP with ASP.NET Web API

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

问题描述

我的工作使用Web API中ASP.MVC MVC 4创建一组新的服务。到目前为止,这是伟大的。我创建了服务,并得到了它的工作,现在我想使用JQuery来使用它。我可以回去使用招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.

我碰到这个<一跑href=\"https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp/blob/master/src/WebApiContrib.Formatting.Jsonp/JsonpMediaTypeFormatter.cs\">JsonpMediaTypeFormatter.将它添加到的Application_Start 您的Global.asax通过这样的:

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);
    }
})

这似乎很好地工作。

It seems to work very well.

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

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