0
votes

I am trying to call my .net Core API from my angular application and I get an error saying

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

I made all the changes to my startup.cs file as specified by Microsoft article, but still getting the above error. Below is my Startup.cs file:

  public void ConfigureServices(IServiceCollection services)
            {



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

                        });
                    });


                    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
                    services.AddControllers();
                   services.AddDbContext<db_recloadContext>();

            }

in my configure method, I have the following code:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }
            else
            {
                app.UseHsts();
            }
            //app.UseCors(MyAllowSpecificOrigins);
            app.UseCors(builder => builder
            .WithOrigins("http://localhost:4200") /* list of environments that will access this api */
            .WithMethods("GET", "OPTIONS") /* assuming your endpoint only supports GET */
            .WithHeaders("Origin", "Authorization") /* headers apart of safe-list ones that you use */
            );


            app.UseHttpsRedirection();
            //app.UseMvc();
            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

I followed the following Microsoft article in order to put the CORS in my startup.cs file.

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

I tried the code given below and I getting this error:

enter image description here

This is the changed code:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder.WithOrigins(new string[] { "http://localhost:4200" }).AllowAnyMethod().AllowAnyHeader();
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
                services.AddControllers();
               services.AddDbContext<db_recloadContext>();

        }

and in the configure method, I have the following code:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

            }
            else
            {
                app.UseHsts();
            }
            app.UseRouting();
            app.UseCors("CorsPolicy");
           app.UseHttpsRedirection();

           app.UseAuthorization();
           app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

below is my entire startup.cs file:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.SpaServices;
using RecLoad.Models.DB;
namespace RecLoad
{
    public class Startup
    {
        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)
        {


            //services.AddCors(options =>
            //{
            //    options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
            //});
            //services.AddCors(options =>
            //{
            //    options.AddPolicy("CorsPolicy",
            //    builder =>
            //    {
            //        builder.WithOrigins("http://localhost:4200")
            //                             .AllowAnyHeader()
            //                            .AllowAnyOrigin()
            //                            .AllowAnyMethod();

            //    });
            //});

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                builder =>
                {
                    builder.WithOrigins(new string[] { "http://localhost:4200", "https://localhost:44378/api/recloadprime" }).AllowAnyMethod().WithHeaders("Access-Control-Allow-Origin:http://localhost:4200");
                });
            });
            //response.Headers.Add("Access-Control-Expose-Headers", "Application-Error");
            //response.Headers.Add("Access-Control-Allow-Origin", "*");
            //services.AddCors(options =>
            //{
            //    options.AddPolicy("AllowAnyCorsPolicy", policy => policy.WithHeaders("Access-Control-Allow-Origin:http://localhost:4200", "Access-Control-Expose-Headers").AllowAnyMethod().AllowAnyOrigin());
            //});



            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
                services.AddControllers();
               services.AddDbContext<db_recloadContext>();
        }

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

            }
            else
            {
                app.UseHsts();
            }

            app.UseCors("CorsPolicy");
           app.UseHttpsRedirection();
            app.UseRouting();

            app.UseAuthorization();
           app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

and below is my controller:

namespace RecLoad.Controllers
{
    [Route("api/[controller]")]
    //[EnableCors("AllowAnyCorsPolicy")]
    public class RecLoadPrimeController : ControllerBase
    {
        private readonly db_recloadContext _context;

        public RecLoadPrimeController(db_recloadContext context)
        {

            _context = context;
        }

        [HttpGet]
        public ActionResult<string> Get()
        {

            return "This is a test";

        }

any help will be greatly appreciated.

2

2 Answers

2
votes

As you see at Microsoft's documentation. First add Cors service

        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
            builder =>
            {
                builder.WithOrigins(new string[] { "http://localhost:4200", "http://yourdomain.com" }).AllowAnyMethod().AllowAnyHeader();
            });
        });

Then use it in Configure method

app.UseCors("CorsPolicy");
1
votes

Remove or comment out app.UseHttpsRedirection(); in the Configure method to make the error go away.