Dadria
Dadria

Reputation: 13

Application using CORS does not work in Azure

I have configured my application to use CORS. All works perfectly in my local environment, but after deploying the app to Azure, we receive the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

When I run the application on my computer and create the origin header using the DHC chrome extension, it does actually work:

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

This is the code/configuration that I use:

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);
    }   
}

and finally the 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>

Why doesn't the above work in the Azure enviroment?

Upvotes: 1

Views: 2309

Answers (2)

user1988330
user1988330

Reputation: 1

I had to enable CORS to my App Service on azure portal

Upvotes: 0

Aliaksei
Aliaksei

Reputation: 26

Since recently Azure API apps (which are now obsolete and were unified into App Services) do not obey the CORS headers defined by code as yours. Deploy to a new App Services instance.

Upvotes: 1

Related Questions