Derek
Derek

Reputation: 5855

Can't enable Cross-Origin Requests (CORS) in ASP.NET Core 1.0

Angular 2 service making a call to an ASP.NET Core 1.0 Web API Controller Class but I get this error:

enter image description here

card.service.ts: Angular 2 code. This runs on http://localhost:3000. I doubt there is a problem here.

import { Injectable } from 'angular2/core';
import { Http, Response } from 'angular2/http';
import { Observable } from 'rxjs/Observable';

import { ICard } from './card';

@Injectable()
export class CardService {
    constructor(private _http: Http) { }

    getCards(): Observable<ICard[]> {
        return this._http.get('http://localhost:8462/api/card')
            .map((response: Response) => <ICard[]>response.json())
            .do(data => console.log("getCards: " + JSON.stringify(data)))
            .catch(this.handleError);
    }

    private handleError(error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || 'Server error')
    }    
}

Startup.cs: ASP.NET Core code. Runs on http://localhost:8462. I believe the fix is to add CORS to my Startup.cs file. I've tried following the ASP.NET docs on CORS, as well as many other CORS guides with no luck.

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

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseIISPlatformHandler();

        app.UseApplicationInsightsExceptionTelemetry();

        app.StaticFiles();

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

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

Upvotes: 4

Views: 1125

Answers (2)

rubiktubik
rubiktubik

Reputation: 1001

I had the same issues. My trick was to put the "UseCors.." before "UseMvc()" :-)

Upvotes: 0

Derek
Derek

Reputation: 5855

I think I figured it out. When I first did File > New Project I selected Windows Authentication. It looks like that is what is causing the error.

I tested it by creating a new project with Windows Authentication and adding CORS to Startup.cs. Got the same error. Did not get the error when I created a new project without Windows Authentication and added CORS.

Upvotes: 1

Related Questions