2014-07-10 46 views
0

所以我有一个Web客户端ShazamClient,我想从中使用jQuery从远程web api,ShazamService获取数据和发布数据。起初我试着直接发布到jQuery中的ShazamService,但得到了与CORS相关的错误,这在ShazamService上没有启用。因此,为了解决这个问题,我想直接将请求从ShazamClient的ControllerApiController转发到ShazamService中相应的方法调用。所以我基本上想:如何将jquery请求从我的服务器直接转发到另一个?

public class ShazamClientController : ApiController // or Controller 
{ 
    public string Upload() 
    { 
     return Request.Forward(@"https:\\shazamservice.com\api\upload"); 
    } 
} 

我在网上找到的大部分都涉及到重定向等 - 有没有一种简单的方法来做到这一点?

+0

确实ShazamService支持JSONP? http://en.wikipedia.org/wiki/JSONP – kinakuta

+0

我读过,jsonp只支持GET(也许是过时的信息?)无论哪种方式,我觉得它很麻烦 - HTTP错误不会触发jQuery'失败'处理程序,甚至是“完整”的处理程序;他们只是安静地死去。 – Rollie

+0

是啊,我不是建议jsonp是一个很好的选择,只是扔它在那里,看看它是否满足您的需求 – kinakuta

回答

0

您可以使用HttpClient并重新使用发送到您的控制器的内容向服务发出请求。这里

0

好吧,如果你的 “代理”,与WebAPI

HTML /网页一个简单的例子:

<h1 id="dataTarget"></h1> 

<script> 
.... 
//Because Web API wants it's own "keyless" format for [FromBody] data (=value) 
var _data = { "": "data foo" }; 

$.post("api/values", _data, function(d) { 
    console.log(d); 
    $("#dataTarget").text(d.foo + ' ' + d.bar); 
}); 

</script> 

使用[FromBody]WebAPI ValuesController行动稍加修改默认脚手架:

// POST api/values 
public async Task<JObject> Post([FromBody]string value) 
{   
    using (var client = new HttpClient()) 
    { 
     /* 
     * See http://www.jsontest.com/#echo for usage 
     * which serves as the "other" service you are "proxying" 
     * 
     * Echoed values will be used in front end html 
     */ 
     return JObject.Parse(await client.GetStringAsync("http://echo.jsontest.com/foo/hello/bar/world")); 
    } 
} 

WebAPI的“魔法”:

Headers inspection

H个...

相关问题