Thinker
Thinker

Reputation: 5356

ASP.net core web API CORS issue with Angular2

I am trying a simple HTTP GET from my angular2 frontend as following:

  getGoals(): Observable<CoreGoalModel[]> {

    let headers = new Headers({ 'Access-Control-Allow-Origin': '*' });
    let options = new RequestOptions({ headers: headers });

    return this.http.get(this.base_url + 'coregoal', options)
    .map(this.extractData)
    .catch(this.handleError);
  }

I have set up CORS in my ASP.Net core backend. I have "Microsoft.AspNetCore.Cors": "1.1.1" in projects.json.

My startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddApplicationInsightsTelemetry(Configuration);

    services.AddScoped<ICoreGoalRepository, CoreGoalRepository>();

    // Enable Cors
    services.AddCors();

    services.AddMvc();

    services.AddSwaggerGen();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, WebAPIDataContext context)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseApplicationInsightsRequestTelemetry();

    app.UseApplicationInsightsExceptionTelemetry();

    app.UseMvc();

    app.UseCors(builder =>
        builder.AllowAnyOrigin()
        .AllowAnyHeader()
        .AllowAnyMethod());

    app.UseSwagger();
    app.UseSwaggerUi();
}

However I still get Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. error.

What am I missing? For now I want to allow all origins, all methods, no restrictions.

Upvotes: 1

Views: 1142

Answers (1)

Thinker
Thinker

Reputation: 5356

The sequence of addCors() and addMVC() was incorrect. addCors() has to come before addMVC()

Upvotes: 3

Related Questions