【问题标题】:CORS issue with ASP.net IdentityASP.net 身份的 CORS 问题
【发布时间】:2014-12-18 16:32:25
【问题描述】:

我正在和我的一个朋友一起做一个 angular.js 项目,我们遇到了一个特定的 CORS(跨源请求)问题。服务器是 Microsoft ASP.NET RESTful API,我将 angular.js 与 Node.js 一起使用。

我们在服务器端启用了 CORS,并且能够获取其他所有内容的响应,接受我们正在使用 ASP.NET 身份的用户登录。我们总是得到相同的错误,我将在下面发布,以及来自客户端的 POST。所以基本上我的问题是,有没有人知道如何解决这个问题?谢谢!

XMLHttpRequest 无法加载 http://lectioserver.azurewebsites.net/api/v1/accounts/login。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'localhost' 不允许访问。响应的 HTTP 状态代码为 400。

function login(username, password) {
        var innerconfig = {
            url: baseUrl + "/api/v1/accounts/login",
            data: {
                username: username,
                password: password,
                grant_type: "password"
            },
            method: "POST",
            headers:
            {
                'Accept': 'text/json'
            }
        };
        return $http(innerconfig).then(onSuccess, requestFailed);
        function onSuccess(results) {
            if (results && results.data) {
                $rootScope.access_token = results.data.access_token;
                return results.data;
            }
            return null;
        }
    }

【问题讨论】:

    标签: javascript c# asp.net angularjs


    【解决方案1】:

    这通常是因为为您提供令牌的应用在 CORS 启动之前启动。 修复它非常容易。你只需要去IdentityConfig.cs,里面有一个叫做

    的函数
    public static ApplicationUserManager Create
      (IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    

    在此处插入以下代码行

    context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
    

    这将为令牌请求启用 CORS。 但问题是,当我们这样做时,其他正常请求将开始抛出错误,因为我们已经授予访问源 * 两次。一旦在身份和其他在cors。 如果您遇到此错误,请在您刚刚粘贴的身份配置中的 cors 代码上使用此 if 语句。

    if(context.Request.ContentType == "text/plain")
    

    【讨论】:

      【解决方案2】:

      尝试在标题中设置内容类型,这可能会解决问题

      headers: { 'Content-Type': 'application/x-www-form-urlencoded' }

      【讨论】:

      • 感谢您的回复。但这并没有解决问题
      猜你喜欢
      • 2015-03-30
      • 1970-01-01
      • 2015-06-21
      • 1970-01-01
      • 2022-11-14
      • 2018-11-15
      • 2017-03-28
      • 2016-02-04
      • 1970-01-01
      相关资源
      最近更新 更多