2012-10-21 122 views
0

我正在关注this tutorial以在Web Form网站中构建我的第一个Asp.net Web API,但我面临一个问题。我已经创建了两个项目:为Web服务 ASP.NET Web API不能从远程服务创建json数据

  • 客户项目定义使用的Web服务

    1. 主体项目

    现在我的问题是,如果我使用网络浏览器ex)http://localhost:39930/api/products/导航到我的web api URL,那么这完美地工作,并根据浏览器返回XML或Json数据。

    但是,如果我使用我的客户网站中的Web服务URL,那么没有任何东西会返回!

    这里是我如何调用Web服务从我的客户网站:

    <table> 
        <thead> 
         <tr> 
          <th>Name</th> 
          <th>Price</th> 
         </tr> 
        </thead> 
        <tbody id="products"> 
        </tbody> 
    </table> 
    
    <script type="text/javascript"> 
        function getProducts() { 
         $.getJSON("http://localhost:39930/api/products", 
          function (data) { 
           $('#products').empty(); // Clear the table body. 
    
           // Loop through the list of products. 
           $.each(data, function (key, val) { 
            // Add a table row for the product. 
            var row = '<td>' + val.Name + '</td><td>' + val.Price + '</td>'; 
            $('<tr/>', { text: row }) // Append the name. 
             .appendTo($('#products')); 
           }); 
          }); 
        } 
    
        $(document).ready(getProducts); 
    </script> 
    

    这里是请求在萤火虫的快照:

    enter image description here

    注意,响应是空的。

    那么,我在这里做错了什么?是否应该添加一些配置来允许远程调用服务?

    在此先感谢。

  • 回答

    1

    这是因为您的主机项目和客户端项目运行在不同的端口上,这违反了相同的原始策略和禁止的策略。在这里看到的细节http://en.wikipedia.org/wiki/Same_origin_policy

    如果你想这个工作,你可以使用jsonp而不是json。看看这篇文章http://www.jquery4u.com/json/jsonp-examples/#.UISVAo3iYsc

    +0

    ...这是一个非常好的文章,以解决这个问题:http://www.west-wind.com/weblog/posts/2012/Apr/02/Creating- A-JSONP格式器换ASPNET的Web-API – Eyad