Search code examples
c#asp.net-corecors

Adding headers to iis static files not working in asp.net CORE


I want to add extra headers like Access-Control-Allow-Origin to my webAPI in order to consume this data in another project. At the moment I'm having this error:

Failed to load http://localhost:49932/api/Restaurantes: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

The 49932 port runs my API and 4200 port is my AngularJS client. I have already tried adding them as suggested in this answer but didn't worked:

in appsettings.json:

{
"ConnectionStrings": {
"ConexaoRestaurante": "data source=DESKTOP-R1CQGV1\\SQLEXPRESS;integrated security=SSPI;"
},
  "Logging": {
  "IncludeScopes": false,
"Debug": {
  "LogLevel": {
    "Default": "Warning"
  }
},
"Console": {
  "LogLevel": {
    "Default": "Warning"
  }
},
"StaticFiles": {
  "Headers": {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Headers": "Content-Type",
    "Access-Control-Allow-Methods": "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH"
     }
   }
 }
}

In the Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        // tried both the commented and uncommented part:
        app.UseStaticFiles(new StaticFileOptions()
        {
            OnPrepareResponse = (context) =>
            {
                // Disable caching for all static files.
                context.Context.Response.Headers["Access-Control-Allow-Origin"] = Configuration["StaticFiles:Headers:Access-Control-Allow-Origin"];
                context.Context.Response.Headers["Access-Control-Allow-Headers"] = Configuration["StaticFiles:Headers:Access-Control-Allow-Headers"];
                context.Context.Response.Headers["Access-Control-Allow-Methods"] = Configuration["StaticFiles:Headers:Access-Control-Allow-Methods"];
            }
        }); 

        /*
        app.UseStaticFiles(new StaticFileOptions()
        {
            OnPrepareResponse = (context) =>
            {
                context.Context.Response.Headers["Access-Control-Allow-Origin"] = "*";
                context.Context.Response.Headers["Access-Control-Allow-Headers"] = "Content-Type";
                context.Context.Response.Headers["Access-Control-Allow-Methods"] = "GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH";
            }
        });
        */

        app.UseMvc();

}

I also tried creating the Web.config which is not created when you start a framework Core project and adding the config as following:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 <system.webServer>
  <httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH" />
    </customHeaders>
  </httpProtocol>
 </system.webServer>
</configuration>

So I guess I'm doing something wrong outside of this part, anyone knows what can be wrong here?


Solution

  • Cors is more than just the headers, refer to this for more info in .NET.

    In order to set CORS in .NET Core you need to add the Cors Services and configure them.

    In the ConfigureServices add the following call:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
    }
    

    And in your Configure method:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        // Shows UseCors with CorsPolicyBuilder.
        app.UseCors(builder =>
           builder.WithOrigins("http://localhost:4200").AllowAnyHeader());
    }