Trouble with CORS Policy and .NET Core 3.1

I'm not sure what I'm missing, but can't seem to get my CORS Policy working with .NET Core 3.1 and Angular 8 client-side.

Startup.cs:

        public void ConfigureServices(IServiceCollection services)
        {
            // ...

            // Add CORS policy
            services.AddCors(options =>
            {
                options.AddPolicy("foo",
                builder =>
                {
                    // Not a permanent solution, but just trying to isolate the problem
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
            });

            services.AddControllers();
        }

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

            app.UseHttpsRedirection();

            // Use the CORS policy
            app.UseCors("foo");

            app.UseRouting();

            app.UseAuthorization();

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

Error Message Client-side:

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

Although I was configuring CORS incorrectly (and the accepted answer below did in fact help with that) the root of issue was unrelated. For additional context, the app was working completely fine when running the API and Angular app using the CLI - I was only having this issue after deploying them both to a web server.

The "actual" issue ended up being related to the SQL connection, which I only discovered after adding flat-file error logging to the API and running a SQL Server trace to find that the app wasn't able to connect to SQL at all.

I would normally expect this to just return a 500 and I would have realized the issue in a matter of 10 seconds - however the CORS mis-configuration meant a 500 was never actually being returned because the CORS middleware failed first. This was immensely frustrating to say the absolute least! . However I want to add that here in case others find themselves in this situation, as I was "chasing the wrong rabbit," if you will. After fixing the CORS configuration, I realized the actual issue was entirely unrelated to CORS.

TL;DR; - Sometimes "Non-CORS" .NET Server-side Errors Can Be Returned as CORS Errors If CORS policies Aren't Set Correctly

References:

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware

https://medium.com/swlh/cors-headers-with-dot-net-core-3-5c9dfc664785

first app.UseRouting(); then app.UseCors("foo");

Change your Configure method like the following :

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

    app.UseHttpsRedirection();



    app.UseRouting();  // first
    // Use the CORS policy
    app.UseCors("foo"); // second

    app.UseAuthorization();

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

It worked for me !

Enable Cross-Origin Requests (CORS) in ASP.NET Core, I want to enable CORS with Asp.Net Core 3.0 API project. the template, except I added CORS settings from the documentation: Enable Cross-Origin Requests (C. .. 3.1 update: CORS and master issue dotnet/AspNetCore. When CORS is enabled with the appropriate policy, ASP.NET Core generally automatically responds to CORS preflight requests. See [HttpOptions] attribute for preflight requests . A CORS preflight request might include an Access-Control-Request-Headers header, which indicates to the server the headers that are sent with the actual request.

Web API is using app.UseHttpsRedirection(); which cause CORS issue if requesting client is not https based. So in order to use it with http client we need to comment or remove that line.

This issue is not with CORS, the https is causing this issue but thrown error is saying its with CORS.

CORS not working in Asp.Net Core 3.0 � Issue #16672 � dotnet , What I searched: CORS, IIS, Web API, Core 3 Help us make content visible complete examples of utilizing CORS in Asp.net Core 3.1 Web API Definitions; Default CORS Policy and Middleware; Multiple CORS Policies an� Enable CORS (cross-origin resource sharing) in ASP.NET Core 3.0 WebAPI. CORS for endpoint routing in easy steps. Access to fetch from origin blocked by CORS policy.

When adding the Cors Service make sure to include .SetIsOriginAllowed((host) => true) after .WithOrigins("http://localhost:4200")

services.AddCors(options => {
            options.AddPolicy("mypolicy",builder => builder
            .WithOrigins("http://localhost:4200/")
            .SetIsOriginAllowed((host) => true)
            .AllowAnyMethod()
            .AllowAnyHeader());
  });

3.1 (LTS) and CORS for Web API � Issue #16242 � dotnet , No 'Access-Control-Allow-Origin' header is present on the requested resource. Thankfully there is Cross Origin Resource Sharing (CORS) which� In Addition, you can see how CORS is important while working with SignalR in .NET Core by reading .NET Core with SignalR Real-Time Charts. Conclusion. In conclusion, think of CORS as a relaxation attempt to the more restrictive Same-Origin policy. On the one side, there is a growing need for security on the web.

Try this util

https://www.nuget.org/packages/Microsoft.AspNetCore.Cors/ Using this you can enable/disable the cors in your .net core application

How to Enable Cross-Origin Requests (CORS) in ASP.NET Core, Now to test our fancy new CORS header (here's where I ended up having issues) … Let's run our app again through dotnet run and hit our� .NET Core 3.1 downloads for Linux, macOS, and Windows. .NET Core is a cross-platform version of .NET, for building apps that run on Linux, macOS, and Windows.

As you are using localhost as http://localhost:4200, then try to set it in your configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => options.AddPolicy("ApiCorsPolicy", build =>
    {                
        build.WithOrigins("http://localhost:4200")
             .AllowAnyMethod()
             .AllowAnyHeader();
        }));
        // ... other code is omitted for the brevity
     }
}

And Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider provider)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseCors("ApiCorsPolicy");
    app.UseHttpsRedirection();
    app.UseAuthentication();
    app.UseMvc();
}

CORS headers with dot net core 3. Setting up a blanket CORS for , Now to test our fancy new CORS header (here's where I ended up having issues) … Let's run our app again through dotnet run and hit our� With ASP.NET Core 3.0, we recommend that all apps that require CORS use the CORS Middleware in tandem with Endpoint Routing. UseCors can be provided with a default policy, and [EnableCors] and [DisableCors] attributes can be used to override the default policy where required.

CORS headers with dot net core 3, Configure the CORS policy by listing individual origins if credentials needs to To fix the issue and still allow any origin you can use this method instead: . NET Core 3.1 API that supports CORS requests from any origin with� Breaking changes for migration from Version 2.2 to 3.1. 01/10/2020; 80 minutes to read; In this article. If you're migrating from version 2.2 to version 3.1 of .NET Core, ASP.NET Core, or EF Core, the breaking changes listed in this article may affect your app.

ASP.NET Core API, NET Core application you'll need to use CORS to get XHR to talk across the to Angular 2.0 and in the process ran into CORS problems. Applies to .NET Core 1 and .Net Core 2 (further down) If using .Net-Core 1.1. Unfortunately the docs are very confusing in this specific case. So I'll make it dead-simple: Add Microsoft.AspNetCore.Cors nuget package to your project; In ConfigureServices method, add services.AddCors();

ASP.NET Core and CORS Gotchas, How Does CORS Work? Inner Workings; Preflight Requests. Demo. Same-Origin Policy in Action; Enabling CORS. Beginning with .NET Core 3.1, these releases will happen every November and every other release will be LTS. Long Term Support (LTS) LTS releases are supported for three years after the initial release.

Comments
  • try to set app.UseCors("foo"); before app.UseHttpsRedirection();
  • @StepUp thanks for the recommendation, but still no luck
  • Have you solved your problem?
  • Have anyone solved this issue? Why no answer is accepted?
  • Yes, sorry I never circled back to this issue after resolving it. I've added an update to the question with some additional context. Thank you!
  • -is there a nuget package necessary?
  • nuget package for cors
  • @chana - you do not need to install nuget package
  • I was stuck on this issue for DAYS! nothing from the internet worked. Your solution combined with OP's ConfigureServices code solved my problem. Thanks a lot!
  • Is it documented anywhere ?
  • That is correct! the line UseHttpsRedirection() must be after UseCors()