【问题标题】:Cross-Origin error with Authorization in AngularJsAngularJs中的授权跨域错误
【发布时间】:2016-12-30 11:15:21
【问题描述】:

我正在尝试从我的 WebAPI 设置授权调用。

方法如下:

    [Authorize]
    [DynamicAuthorizeGroupRoles(DRoles = "Failures")]
    [HttpGet]
    [Route("Authorization/Test")]
    public HttpResponseMessage GetTest()
    {
        Logger.Write(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
        return "Access granted".ToJSONResponse();
    }

如果我直接从浏览器调用它,它工作正常。但是,当我从 AngularJS 页面执行此操作时,出现以下错误:

跨域请求被阻止:同源策略不允许读取位于http://.../Authorization/Test 的远程资源。 (原因:CORS 标头 'Access-Control-Allow-Origin' 不匹配 '')。*

这是我的配置的样子:

public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute("*", "*", "*");
            cors.SupportsCredentials = true;
            config.EnableCors(cors);
            // Web API routes
            config.MapHttpAttributeRoutes();
        }
    }

Globals.asax.cs:

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            EnableCrossDomainCall();                
        }

        /// <summary>
        /// Enable cross domain call
        ///     To Use post requests between domain
        /// </summary>
        private void EnableCrossDomainCall()
        {


            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {

                Context.Response.AddHeader("Access-Control-Allow-Origin", Context.Request.Headers["Origin"]);
                Context.Response.AddHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
                Context.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
                Context.Response.AddHeader("Access-Control-Allow-Credentials", "true");

            }

        }

我尝试了几次都没有成功。知道为什么会发生这种情况或我需要改变什么吗?

【问题讨论】:

  • 对不起,但这对我没有帮助。我知道基础知识,但是通过上述配置,所有其他 webapi 调用都可以正常工作。我只对发布的授权有问题。知道为什么吗?

标签: c# angularjs authorization cross-domain


【解决方案1】:

不是您的 WebApi 项目有 CORS 问题。将跨域文件放在托管 Angular 的站点的 Web 根目录中。如果您使用 IIS 为网站提供服务,请添加 <location path="crossdomain.xml"> <system.webServer> <staticContent> <clear /> <mimeMap fileExtension=".xml" mimeType="text/x-cross-domain-policy" /> </staticContent> </system.webServer> </location> 到宿主网站的webconfig

【讨论】:

    猜你喜欢
    • 2014-03-10
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 2013-09-11
    • 2023-03-24
    • 2020-09-18
    相关资源
    最近更新 更多