2015-09-23 48 views
1

我已經能夠從 /節點應用撥打電話蠻好網絡API當我使用$ SCE的IFrame,但現在我想從應用程序中的jquery ajax調用Web Api。401未授權的AJAX調用網絡API 2應用

當我嘗試調用它,我得到

401未授權

function getComments() { 
    $.ajax({ 

     url: 'http://localhost:17308/Home/GetNewsComments?id=' + group, 
     type: 'Get', 
     data: { id: tipId }, 
     success: function (data) { 
      $("#commentDetail").empty().append(data); 
     }, 
     error: function() { 
      //alert("something seems wrong"); 
      console.log("something is wrong"); 
     } 
    }); 
}; 

FYI/BTW

我已經能夠撥打電話的iframe與

$scope.setTipId = function (id) { 
    $scope.detailFrame = $sce.trustAsResourceUrl("http://localhost:17308/Home/GetNewsComments?id=" + id); 

我可以爲我的控制器的jquery ajax調用做類似的事嗎?

更新

我甚至嘗試了 「角辦法」

$http.get('http://localhost:17308/CommentCount/').success(function (data) { 
     console.log('made it'); 
    }) 
    .error(function() { 
     console.log('error'); 
    }); 

我仍然得到401錯誤...

回答

1

那麼,這一個有點痛苦,但這將工作。注意:您現在必須都得到與JSONP電話,沒有更多的定期JSON的dataType ...

閱讀並遵守這裏說明:

http://www.codeproject.com/Tips/631685/JSONP-in-ASP-NET-Web-API-Quick-Get-Started

接下來,做所有的痛苦的NuGet安裝,卸載和更新,我記得它與json formatmatter,web api,cors和newtonsoft json之間的衝突有點痛苦。

的持續性就會還清

jQuery的通話

$.ajax({ 
     url: 'http://localhost:17308/Home/GetNewsComments?id=' + group, 
     type: 'Get', 
     data: { id: tipId }, 
     contentType: 'application/json; charset=utf-8', 
     dataType: "jsonp", 
     callback: 'callbackFunc', 
     success: function (data) { 
      var json = $.parseJSON(data); 
      console.log(json); 
     }, 
     error: function (xhr, status, error) { 
      console.log(xhr + '\n' + status + '\n' + error); 
     } 
    }); 

function callbackFunc(resultData) { 
    console.log(resultData); 
} 

我假設你注意,並有網絡API,JSON格式,CORS,與其他System.Web.Http更新,並沿其他依賴關係。

所以的這部分客戶端,但最終還是發生了很多做服務器端網頁API

+0

的確對那些依賴關係感到痛苦。最後雖然工作,我不明白爲什麼我所有的JSON調用現在都必須是JSONP,我看到他們與一個.net Web窗體應用程序失敗,調用新修改的Web API服務項目,現在他們都必須是JSONP –

1

的網絡API控制裝置的呼叫和加載的iFrame是根本不同的東西。

我懷疑你的控制器方法實際上是需要某種授權。裝飾Web API控制器或控制器方法,其屬性如下所示[AllowAnonymous]。如果這不是一個選項,你的問題是你沒有一個有效的ASP.NET會話,或者不在你的http調用中添加令牌來授權。

[AllowAnonymous] //This allows all methods in the Controller to be accessed anonymously. Both are redundant in this case. 
public class CommentCountController : ApiController 
{ 
    [HttpGet] 
    [AllowAnonymous] //This allows this method to be accessed anonymously . Both are redundant in this case. 
    public int Get() 
    { 
     return 1; 
    } 
} 
+0

沒有使用JSONP用,這不是它。我嘗試了這些屬性。我已經啓用了CORS,並且一個asp.net web Forms應用程序能夠從另一個端口等連接/調用它...這是Angular/Node應用程序使用整個$ sce.trustAsResourceUrl HAD來使用以便甚至可以調用MVC控制器來工作。 MVC控制器像Web Api一樣是RESTful,事實上控制器實現了apicontroller所以我99%肯定它是Angular/Node應用程序的一個問題 –

+0

您的問題必須是越過的身份驗證方法。您的服務器代碼被鎖定,而且Angular沒有提供正確的憑據。如果使用令牌認證,則需要確保您的請求在來自角度的所有傳出$ http調用的授權標頭中包含令牌。 –

+0

如何添加令牌? –