11

I am having some trouble allowing cors. I have set server side like so:

  app.UseCors(builder => builder.WithOrigins("http://localhost:4200/").AllowAnyHeader());

Inside of the configure method of the startup class

When the my web API is hit, it will return the data fine.

However, the problem seems to be with Angular as in the I get the following error:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

Here is my angular web api call

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';;


@Injectable()
export class ProfileService {

    private baseUrl = 'api/profile/';

    constructor(private http: HttpClient) { }

    getLookups(step: number) {
        return this.http.get('http://localhost:51658/' + this.baseUrl + 'lookups/' + step)
    }

}
Ben Donnelly
  • 1,191
  • 5
  • 13
  • 30
  • 2
    Do you get any exceptions in your ASP.NET Core application? If yes, be aware that exceptions will **CLEAN** of any CORS headers set by the CORS middleware – Tseng Jan 26 '18 at 15:08
  • @Tseng, thank you so much - interesting tidbit. Could you ellaborate or point to any docs on this? I think we’ve been running into this forever – KyleMit Jul 20 '21 at 01:37

7 Answers7

18

Changed builder.WithOrigins("http://localhost:4200/") to

builder.WithOrigins("http://localhost:4200")

(Removed the '/')

Ben Donnelly
  • 1,191
  • 5
  • 13
  • 30
  • I feel like i spend hours on this problem every time I am setting up a new project and this ends up being what the cause is. – Nick Rubino Mar 02 '20 at 03:08
17

change your line in API with :

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

be sure you added Services.AddCors(); in ConfigureServices() stop the server and run again after changes are made.

  • `AllowAnyCredentials` shows up in red in ASP.NET Core 2.1. Is that in another package? – James Poulose Nov 24 '18 at 04:46
  • 5
    @JamesPoulose It should just be .AllowCredentials() – Rohit Ramname Apr 12 '19 at 17:28
  • that's the only solution that worked for me. I was having this issue with react – luturol Jul 21 '19 at 18:38
  • 3
    Got exception after repeat your code. -- System.InvalidOperationException: 'The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the CORS policy by listing individual origins if credentials needs to be supported.' -- Remove .AllowCredentials helped me – Mateech Mar 02 '20 at 17:05
  • This might lead to an exception in Asp.net core >3.0: The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the CORS policy by listing individual origins if credentials needs to be supported – raw Oct 08 '20 at 13:30
7

"WithOrigins" expect an array, not a string so maybe this is your case. However the minimum requirements for Cors to works in your case are:

In Startup.cs to add services.AddCors(); before services.AddMvc(); and also:

string[] origins = new string[] { "http://localhost:4200" }; app.UseCors(b=>b.AllowAnyMethod().AllowAnyHeader().WithOrigins(origins));

Again add it before app.UseMvc(your routes ...)

Or what you actually need doesn't matter the technology is to add a "Access-Control-Allow-Origin" header with value the origin/origins in the response of the server which in .Net core 2 can be done like this (in any method in a controller):
ControllerContext.HttpContext .Response .Headers .Add("Access-Control-Allow-Origin","http://localhost:4200");

or globally - you can create a middleware that add this header to all the responses when the origin match. Works also in Angular 6 and .Net Core 2 as separate applications.

Pavel Aslanov
  • 180
  • 2
  • 6
  • 2
    `WithOrigins` expects a `params string[]` - that means multiple separate string parameters. A single `string` parameter is perfectly fine. – James Poulose Nov 24 '18 at 04:50
1

The answer is correct but still, for some people, it might not work the reason is the placement of statements. You must write all CORS related statements before useMvc()/addMvc.

In Asp net Core. The syntax will look like

In ConfigureServices method

services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins("http://localhost:4200");
                });
            });

// make sure the cors statement is above AddMvc() method.
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

In the Configure method

 app.UseCors(MyAllowSpecificOrigins);

 // make sure cors is above add UseMvc method.
 app.UseMvc();

Here MyAllowSpecificOrigins is just a policy name and you can define at the top of your class

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

I hope it helps.

1

U can configure Cors service by adding default policy in ConfigureServices

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder =>
                    {
                        builder.WithOrigins("http://localhost:4200");
                    });
            });

            .... add other services
        } 

and don't forget to add UseCors in Configure

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                .. other middlewares 
                app.UseCors();
                app.UseRouting();
                .. other middlewares 
    
            }
hanan
  • 1,768
  • 1
  • 14
  • 19
0

Also try to add AllowAnyMethod to the chain.

builder.WithOrigins("http://localhost:4200/").AllowAnyMethod().AllowAnyHeader()
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
-2

Am serving angular on other port like :4200 or :4300 depending on the number of ports in use

so I have configured my asp.net core app in

startup.cs

file to allow CORS from other sites

public class Startup
{


    readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {



        var config = new AutoMapper.MapperConfiguration(cfg =>
        {
            cfg.DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();
            cfg.AddProfile(new ApplicationMappingProfile());
        });
        var mapper = config.CreateMapper();
        services.AddSingleton(mapper);
        services.AddCors(options =>
{
    options.AddPolicy(MyAllowSpecificOrigins,
    builder =>
    {
        builder.WithOrigins("http://localhost:4200",
                            "http://localhost:4300")
                            .AllowAnyHeader()
                            .AllowAnyMethod();
    });
});
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);


        // Add EntityFramwork support for sqlServer
        services.AddEntityFrameworkSqlServer();

        //Add APplicationDbContext
        services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

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

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();


        }
        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();
        }
        //create a service scope to get an ApplicationDbcontext instance using DI
        using (var serviceScope =
            app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var dbContext =
                serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
            //create the db if it doesn;t exist

            dbContext.Database.Migrate();
            DbSeeder.Seed(dbContext);
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseSpaStaticFiles();
        app.UseCors(MyAllowSpecificOrigins); 
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{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");
            }
        });
    }
}

please read asp.net core documentation

Eyayu Tefera
  • 771
  • 9
  • 9