簡體   English   中英

來自調用 Web Api 2 應用程序的 Angular 節點應用程序的 401 未經授權的 ajax 調用

[英]401 Unauthorized ajax call from angular node application calling Web Api 2 application

我已經能夠當我使用$ SCEiFrame從一個/節點應用撥打電話蠻好的Web API,但是現在我想在應用程序內從jQuery的AJAX調用Web API。

當我嘗試調用它時,我得到

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

僅供參考/順便說一句

我已經能夠調用 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 錯誤...

調用Web Api控制器和加載iFrame是根本不同的事情。

我懷疑您的控制器方法實際上需要某種授權。 如下所示,使用屬性[AllowAnonymous]裝飾Web Api Controller或Controller方法。 如果這不是一種選擇,則您的問題是您沒有有效的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;
   }
}

好吧,這有點痛苦,但這會起作用。 注意:您現在必須使用jsonp進行所有GET調用,不再需要常規的json dataType ...

閱讀並遵循此處的指示:

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

接下來,完成所有痛苦的Nuget安裝,卸載和更新,我記得json格式問題,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);
}

我假設您已經注意了,並更新了Web Api,json格式程序,CORS以及其他System.Web.Http和其他依賴項。

因此,這部分客戶端 ,但最終很多與服務器端有關的事情與您在Web API中使用JSONP有關

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM