1

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.

1
  • FYI, you probably want to remove the line adding the Access-Control-Allow-Origin to your request. That header needs to be added by your server side code in its responses - makes no sense to send it as a request header. Commented Mar 31, 2017 at 9:58

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Also note if you are using static files middleware you also need to put it before it. The requests are always handled in the order they are registered (the :UseXxx calls)

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.