使用CORS的应用程序在Azure中不起作用

时间:2016-02-16 12:31:46

标签: c# asp.net azure cors

我已将我的应用程序配置为使用CORS。所有这些都在我的本地环境中完美运行,但在将应用程序部署到Azure后,我们收到以下错误:

  

请求时没有'Access-Control-Allow-Origin'标头   资源。

当我在计算机上运行应用程序并使用DHC chrome扩展程序创建原始标题时,它确实有效:

Access-Control-Allow-Credentials:   true
Access-Control-Allow-Origin:        http://mysite.s3-website-eu-west-1.amazonaws.com
Access-Control-Expose-Headers:      Location,Finished

这是我使用的代码/配置:

的Global.asax.cs

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
}

WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    config.EnableCors(new MyCorsPolicyAttribute());
    config.MapHttpAttributeRoutes();
}

MyCorsPolicyAttribute.cs

public class MyCorsPolicyAttribute : Attribute, ICorsPolicyProvider
{
    private CorsPolicy _policy;

    public MyCorsPolicyAttribute()
    {
        _policy = new CorsPolicy
        {                
            AllowAnyMethod = true,
            AllowAnyHeader = true,
            SupportsCredentials = true
        };

        _policy.ExposedHeaders.Add("Location");
        _policy.ExposedHeaders.Add("Finished");

        // Add allowed origins.
        _policy.Origins.Add("http://mysite.s3-website-eu-west-1.amazonaws.com");
        _policy.Origins.Add("http://localhost:81");//for testing purposes; 
   }
    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request)
    {
        return Task.FromResult(_policy);
    }

    public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        return Task.FromResult(_policy);
    }   
}

最后是 web.config

<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
    <remove name="WebDav" />
    <remove name="OPTIONSVerbHandler" />
    <remove name="TRACEVerbHandler" />
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
</system.webServer>

为什么上述工作在Azure环境中不起作用?

2 个答案:

答案 0 :(得分:1)

最近,Azure API应用程序(现已过时并统一到App Services中)不遵守代码定义的CORS标头。部署到新的App Services实例。

答案 1 :(得分:0)

我必须在天蓝色门户网站上启用CORS到我的应用服务