2012-10-21 48 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