1
votes

I have enabled CORS in my ASP.NET MVC API, with this code:

        public static void Configure(IApplicationBuilder app)
        {
            app.UseCors("CorsName");
        }
        public static void ConfigureServices(IServiceCollection services, IConfiguration config)
        {
            // Configuration and adding Cross-origin resource sharing
            services.AddCors(options =>
            {
                options.DefaultPolicyName = "CorsName";
                options.AddPolicy("CorsName", builder =>
                {
                    builder
                        .WithOrigins(config["AppSettings:CorsOrigin"])
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials()
                        .AllowAnyOrigin()
                        .Build();
                });
            });
        }

I try to get data from API, opening the localhost:6320/api/users and it works, I get all the data. Now when I try to get data from Angular 7 app, the data is not loaded and there is an error

"Access to XMLHttpRequest at 'http://localhost:6320/api/users' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Why there is an error when trying to get data from Angular app if I have enabled CORS?

Here is the AppSettings

  "AppSettings": {
    "DashboardUrl": "http://127.0.0.1:4200",
    "CorsOrigin": "http://localhost:4200"
  }

Startup configuration from Startup.cs

        public Startup(IHostingEnvironment env, IConfiguration configuration)
        {
            Configuration = configuration;

            HostingEnvironment = env;
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment hEnv)
        {
            InitializeIdentityDbAsync(app.ApplicationServices).Wait();
            DiagnosticsStartup.Configure(app, hEnv);
            CorsStartup.Configure(app);
            IdentityStartup.Configure(app, Configuration);
            MVCStartup.Configure(app);
        }
                public void ConfigureServices(IServiceCollection services)
        {
        CorsStartup.ConfigureServices(services, Configuration);
        services.AddAutoMapper();
        services.AddSingleton<IConfiguration>(o => Configuration);
        services.AddScoped<IAppContext, AppContext>();
        services.AddSingleton<IEmailService, EmailService>();
            services.AddScoped<AuthService>();
            services.AddScoped<UserService>();
            EFStartup.ConfigureServices(services, Configuration);
            IdentityStartup.ConfigureServices(services, HostingEnvironment, Configuration);
            MVCStartup.ConfigureServices(services);
            AutoMapperConfig.RegisterMappings(services.BuildServiceProvider());
        }
3
Do you want to authorize all origins? You are calling WithOrigins(config["AppSettings:CorsOrigin"]) and AllowAnyOrigin(). Also verify your config["AppSettings:CorsOrigin"] returns the good value.youri
Please add the full Startup.Configure implementation.Jota.Toledo

3 Answers

0
votes

You're adding origins twice. First, through the .WithOrigins(config["AppSettings:CorsOrigin"]), then through .AllowAnyOrigin(). If only a specific origin is allowed(which I suppose is true considering your configuration), remove the .AllowAnyOrigin() call.

Try with:

services.AddCors(options =>
{
    options.AddPolicy("CorsName", builder =>
    {
        builder
            .WithOrigins(config["AppSettings:CorsOrigin"])
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
    });
});

Check what you're getting from config["AppSettings:CorsOrigin"]. Do you have a key called AppSettings?

Futhermore, it might be(and most probably is) that you're calling app.UseMvc(); before app.UseCors();. Make sure your Configure method has the following order:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    app.UseCors("CorsName");
    app.UseMvc();
}
0
votes

Remove this from your startup class:

services.AddCors(options =>
{
    options.AddPolicy("CorsName", builder =>
    {
        builder
            .WithOrigins(config["AppSettings:CorsOrigin"])
            .AllowAnyHeader()
            .AllowAnyMethod()
            .AllowCredentials();
    });
});

and in the Configure method try this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    app.UseCors(builder => {
        builder
        .WithOrigins(config["AppSettings:CorsOrigin"])
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials();
     });
    app.UseMvc();
}

If works in this way so you have a problem with the Policy and their assignment to the UseCors method.

-1
votes

you have to enable CORS in front end also.Following is one of the many ways how you can enable CORS in angular .

step 1: Create proxyconfig.json file inside main project folder(beside src and node_modules).

step 2:

{
  "/api": {
  "target":"url to the server", (eg: "http://45.33.74.207:3000")
  "secure": false,
  "changeOrigin": true
  }
}

save it inside proxyconfig.json file.

step 3: add --proxy-config proxyconfig.json in start inside scripts object

"start": "ng serve --proxy-config  proxyconfig.json"

inside package.json file.

step 4: save and start the project with npm start

note: if you start project with (ng serve) it will not work.