3

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?

3
  • Probably, helps this. blog.thunderstrucksolutions.se/… Commented Feb 6, 2018 at 1:46
  • I don't know why but i'm having ERR_CONNECTION_TIMED_OUT when trying to access your link, can you export it to pastebin.com please? I'm in a hurry here... Commented Feb 6, 2018 at 1:58
  • 1
    cached url: webcache.googleusercontent.com/… Commented Feb 6, 2018 at 2:07

2 Answers 2

0

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());
}
Sign up to request clarification or add additional context in comments.

Comments

0

Use bottom code [reference]:

app.UseStaticFiles(new StaticFileOptions()
{
    OnPrepareResponse = context =>
    {
        context.Context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        context.Context.Response.Headers.Add("Access-Control-Allow-Methods", "POST, GET, DELETE, PUT, PATCH, OPTIONS");
    }

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.