简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM