【问题标题】:401 Unauthorized ajax call from angular node application calling Web Api 2 application401 来自 Angular 节点应用程序调用 Web Api 2 应用程序的未经授权的 ajax 调用
【发布时间】:2015-09-25 08:29:31
【问题描述】:

当我将 $sce 用于IFrame,但现在我想在应用程序中从 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 错误...

【问题讨论】:

    标签: javascript jquery ajax angularjs asp.net-web-api


    【解决方案1】:

    调用 Web Api 控制器和加载 iFrame 是完全不同的事情。

    我怀疑您的控制器方法实际上需要某种授权。使用属性[AllowAnonymous] 装饰 Web Api 控制器或控制器方法,如下所示。如果这不是一个选项,您的问题是您没有有效的 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;
       }
    }
    

    【讨论】:

    • 不,不是这样。我尝试了这些属性。我已经启用了 CORS,并且一个 asp.net Web 表单应用程序能够从不同的端口等很好地连接/调用它......这是 Angular /Node 应用程序的东西,这整个 $sce.trustAsResourceUrl 必须用于甚至调用 MVC 控制器来工作。 MVC 控制器像 Web Api 一样是 RESTful,实际上控制器实现了 apicontroller 所以我 99% 确定这是 Angular/Node 应用程序的问题
    • 您的问题必须是越界的身份验证方法。您的服务器代码被锁定,Angular 没有提供正确的凭据。如果令牌身份验证,您需要确保您的请求在所有来自 angular 的传出 $http 调用的 Authorization 标头中都有令牌。
    • 如何添加令牌?
    • 你的系统是用什么来授权的?你必须被授予一个令牌,你可以像本教程一样追加 -bitoftech.net/2014/06/09/…
    猜你喜欢
    • 2017-07-15
    • 2017-04-22
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 2017-06-01
    • 1970-01-01
    • 2018-09-12
    • 2021-02-26
    相关资源
    最近更新 更多