2

I am trying to connect to my .net core API from angular application. when I try to do that, I get an error saying:

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

below is the console messages from my angular application:

enter image description here

Here is what I did to resolve the error. I added services.addCors in ConfigureServices method in startup.cs file:

public void ConfigureServices(IServiceCollection services)
    {

        services.AddCors(options =>
        {
            options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
        });

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

    }

In configure method, I put the following code:

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

            }
            else
            {
                app.UseHsts();
            }
           app.UseCors("AllowAnyCorsPolicy");
           app.UseHttpsRedirection();
           app.UseRouting();
           app.UseAuthorization();
           app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

In my controller, I have the following code:

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

        public RecLoadPrimeController(db_recloadContext context)
        {

            _context = context;
        }

I followed the instruction given in Microsoft documentation and one of the stackoverflow post:

https://stackoverflow.com/questions/42199757/enable-options-header-for-cors-on-net-core-web-api

and Microsoft article:

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

I spend lot of time going through other documentation and tried different code in startup.cs file, but this error is not going away.

Below is my api that runs fine:

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

            return "This is a test";

        }

Below is the header from my developers tool:

enter image description here

I also enabled CORS extension in my chrome browser. Below is the image:

enter image description here

Any help will be highly appreciated.

Anjali
  • 2,540
  • 7
  • 37
  • 77

1 Answers1

7

To make it work, you could try these things:

1) in ConfigureServices method, call AddCors to configure the CORS service, initially, to allow any origin:

services.AddCors(options => 
{
    options.AddPolicy("AllowAnyCorsPolicy", policy => policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
});

2) in Configure method add UseCors, this adds middleware to web application pipeline:

app.UseRouting();
app.UseCors("AllowAnyCorsPolicy");
app.UseMvc();

Since ASP.NET Core 3.1 .UseCors() needs to be called after .UseRouting(), as mentioned in https://github.com/dotnet/aspnetcore/issues/17830.

When this initial configuration is working, it can be later modified to your requirements.

Martin Staufcik
  • 8,295
  • 4
  • 44
  • 63
  • I put the exact code in my application that you gave me. I am getting a different error: InvalidOperationException: Endpoint RecLoad.Controllers.RecLoadPrimeController.Get (RecLoad) contains CORS metadata, but a middleware was not found that supports CORS. Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code. The call to app.UseAuthorization() must appear between app.UseRouting() and app.UseEndpoints(...). – Anjali Mar 30 '20 at 05:35
  • This guide mentions in ASP.NET 2.2 this was working, migration guide says you need to use .UseCors() after .UseRouting(): https://github.com/dotnet/aspnetcore/issues/17830 – Martin Staufcik Mar 30 '20 at 05:42
  • Modified the answer. – Martin Staufcik Mar 30 '20 at 05:48
  • 1
    I put the useRouting in Configure method and now when I run the api, I am getting three errors now: 1) Access to XMLHttpRequest at 'https://localhost:44378/api/recloadprime' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 2) ERR_failed and last one HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", – Anjali Mar 30 '20 at 17:57
  • any help on this will be really appreciated. – Anjali Mar 30 '20 at 22:27
  • I created a new solution with two project, one api project in ASP.NET Core 3.1 and another web project for the javascript client of the API. I tried to reproduce the error from the code you posted here, but could not reproduce it, CORS was working. What I found is, `.UseCors()` needs to be after `.UseRouting()` , and another thing the attribute `EnableCors` is not needed, sorry, it works even without it if there is the policy used with `.UseCors(...policyName)`. – Martin Staufcik Mar 31 '20 at 11:33
  • Doesn't work in Core 5.0 webapi – djack109 Dec 29 '21 at 18:04