请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许来源'http:// localhost:3000'访问

时间:2016-10-06 07:20:46

标签: asp.net-web-api

我有一个ASP.NET Web API 2应用程序(在Azure中托管)和Angular JS中的前端。当我尝试调用任何控制器方法时,我收到以下错误:

XMLHttpRequest无法加载https:// ........请求的资源上没有“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:3000”访问。

这是我的配置代码在Startup类中的外观。

public void Configuration(IAppBuilder app)
    {
        // setup cors policy
        var corsPolicy = new CorsPolicy
        {
            AllowAnyOrigin = true,
            //AllowAnyHeader = true,
            //AllowAnyMethod = true,   
            SupportsCredentials = true
        };

        // add headers
        foreach (var hdr in new string[] { "Authorization", "Content-Type", "Origin", "X-Requested-With", "Accept", "Cache-Control" }) { corsPolicy.Headers.Add(hdr); }

        // add methods
        foreach (var mth in new string[] { "GET", "POST", "PUT", "DELETE", "OPTIONS" }) { corsPolicy.Methods.Add(mth); }

        // add origins
        var allowedOrigins = ConfigurationManager.AppSettings["AllowedOrigins"];
        if (allowedOrigins != null)
        {
            var origins = allowedOrigins.Split(',').Select(x => x.Trim());
            if (origins.Any())
            {
                if (!origins.Contains("*"))
                {
                    corsPolicy.AllowAnyOrigin = false;

                    // add each whitelisted origin
                    foreach (var origin in origins) { corsPolicy.Origins.Add(origin); }
                }
            }
        }

        // setup cors options
        var corsOptions = new CorsOptions
        {
            PolicyProvider = new CorsPolicyProvider { PolicyResolver = context => Task.FromResult(corsPolicy) }
        };

        // enable cors
        app.UseCors(corsOptions);


        // setup JWT tokens auth
        ConfigureOAuthTokenGeneration(app);
        ConfigureOAuthTokenConsumption(app);


        var httpConfig = new HttpConfiguration();

        ConfigureWebApi(httpConfig);

        app.UseWebApi(httpConfig);

    }

1 个答案:

答案 0 :(得分:0)

您可以在Azure网络应用中设置CORS值中的(*),以防止发生原始错误。

https://azure.microsoft.com/en-in/documentation/articles/app-service-api-cors-consume-javascript/