Search code examples
angularasp.net-coreheadercors

CORS Error, can't receive data from asp.net core backend


I'm just getting started with web services. I created an asp.net core app with angular frontend.

I've already added CORS to my web service startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        //services.AddControllersWithViews();
        services.AddControllers();

        services.AddDbContext<BuchverwaltungDbContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

        // In production, the Angular files will be served from this directory
        //services.AddSpaStaticFiles(configuration =>
        //{
        //    configuration.RootPath = "ClientApp/dist";
        //});
        services.AddCors();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseCors(options =>
        options.WithOrigins("http://localhost:4200/")
        .AllowAnyMethod()
        .AllowAnyHeader());

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            //Swagger hier einbauen
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        if (!env.IsDevelopment())
        {
            app.UseSpaStaticFiles();
        }

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
        });

        app.UseSpa(spa =>
        {
            // To learn more about options for serving an Angular SPA from ASP.NET Core,
            // see https://go.microsoft.com/fwlink/?linkid=864501

            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }
}

And here is how I try to the books in the angular Frontend:

getBooks() {
return this.http.get(this.baseURL + "/books")
.toPromise()
.then(res => this.books = res as Book[]);}

Somehow the Error still shows up on the console:

Access to XMLHttpRequest at 'https://localhost:44302/api/books' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When opening my API in the browser (https://localhost:44302/api/books), all the data show up correctly.


Solution

  • According to docs:

    The call to UseCors must be placed after UseRouting, but before UseAuthorization. For more information, see Middleware order.

    So simply change your order of calling methods in Configure method.

    Update based on comments

    Also remove trailing slashes from origin. Ex.: WithOrigins("http://localhost:4200") instead of WithOrigins("http://localhost:4200/").

    CORS header requires protocol and domain (http://localhost:4200), not endpoint (http://localhost:4200/).