317

I am trying to enable cross origin resources sharing on my ASP.NET Core Web API, but I am stuck.

The EnableCors attribute accepts policyName of type string as parameter:

// Summary:
//     Creates a new instance of the Microsoft.AspNetCore.Cors.Core.EnableCorsAttribute.
//
// Parameters:
//   policyName:
//     The name of the policy to be applied.
public EnableCorsAttribute(string policyName);

What does the policyName mean and how can I configure CORS on an ASP.NET Core Web API?

Grigory Zhadko
  • 1,484
  • 1
  • 19
  • 33
Oluwafemi
  • 14,243
  • 11
  • 43
  • 59

23 Answers23

499

For ASP.NET Core 6:

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("http://example.com",
                                              "http://www.contoso.com");
                      });
});

// services.AddResponseCaching();

builder.Services.AddControllers();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapControllers();

app.Run();

See the official docs for more samples.


For ASP.NET Core 3.1 and 5.0:

You have to configure a CORS policy at application startup in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.WithOrigins("http://example.com")
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));

    // ...
}

The CorsPolicyBuilder in builder allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:

[EnableCors("MyPolicy")]

Or apply it to every request:

public void Configure(IApplicationBuilder app)
{
    app.UseCors("MyPolicy");

    // ...

    // This should always be called last to ensure that
    // middleware is registered in the correct order.
    app.UseMvc();
}
Himanshu
  • 31,810
  • 31
  • 111
  • 133
Henk Mollema
  • 44,194
  • 12
  • 93
  • 104
  • 23
    I found that app.UseCors("MyPolicy") didn't work for my API endpoints. I needed to explicitly [EnableCors("MyPolicy")] on the controller endpoints in question. – robbpriestley Jun 15 '16 at 01:26
  • 20
    From [the official docs](https://learn.microsoft.com/en-us/aspnet/core/security/cors#enabling-cors-with-middleware): "To enable CORS for your entire application add the CORS middleware to your request pipeline using the `UseCors` extension method. Note that the CORS middleware must precede any defined endpoints in your app that you want to support cross-origin requests (ex. before any call to `UseMvc`)." – Alex Klaus Oct 12 '17 at 03:12
  • 5
    I added app.UseCors() after app.AddMvc() and it didn't work. Because order of Use methods affects how the middleware works! – Obay Abd-Algader Nov 06 '18 at 11:39
  • 5
    Are there any risks of allowing any origin? – Percy Apr 09 '19 at 13:39
  • 4
    This answer didn't work for me, because of missing Microsoft.AspNetCore.Cors nuget package. – Reven Jul 21 '19 at 11:11
  • Not need to explicitly importing Microsoft.AspNetCore.Cors, while I am using .net core 3.1. – ZZZ Dec 04 '19 at 03:49
  • I've got this error: 'EnableCorsAttribute' does not contain a constructor that takes 1 arguments – William Mar 14 '21 at 07:50
  • 1
    @robbpriestley your comment was the key to unlock this for aspnetcore2.2 after 3 days of fighting the code. Thank you! I did find that it was good enough to place the attribute on top of the controller class, saving you needing to do it for each method, if that's what you want. But crucially, NOT on the controller base class (which I tried on day 2 without thinking that was the problem!) – Adam Diament May 11 '21 at 07:11
  • 1
    With AllowCredentials, only exact urls will work, like "http://localhost:49937". Without the port, this did not work. – cskwg Jul 24 '21 at 08:10
  • I've tried everything every docs say, including all the code here on Net5 and nothing works - still get CORS errors trying to call my API from my WebMvc project, all on localhost. What I need, I think, is a witch doctor – PandaWood Mar 30 '22 at 08:03
  • 1
    My witch-doctor came through with an answer.... I needed to use/add authorization. I didn't think I used any and have such a basic site, I didn't care... and none of the docs with code mentioned that authorization is absolutely required... but without authorization... adding CORS in any way or shape, wouldnt work – PandaWood Mar 30 '22 at 09:28
  • 3
    To avoide names you can use AddDefaultPolicy – NiB Jun 12 '22 at 20:48
139

Applies to .NET Core 1 and .Net Core 2

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();

  • In Configure method, before calling app.UseMvc() and app.UseStaticFiles(), add:

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

That's it. Every client has access to your ASP.NET Core Website/API.


If using .Net-Core 2.0

  • Add Microsoft.AspNetCore.Cors nuget package to your project

  • in ConfigureServices method, before calling services.AddMvc(), add:

      services.AddCors(options =>
         {
             options.AddPolicy("AllowAll",
                 builder =>
                 {
                     builder
                     .AllowAnyOrigin() 
                     .AllowAnyMethod()
                     .AllowAnyHeader()
                     .AllowCredentials();
                 });
         });
    
  • (Important) In Configure method, before calling app.UseMvc(), add app.UseCors("AllowAll");

    "AllowAll" is the policy name which we need to mention in app.UseCors. It could be any name.

phoenix
  • 7,988
  • 6
  • 39
  • 45
Vahid Amiri
  • 10,769
  • 13
  • 68
  • 113
  • 2
    true, thought i can enable just one of them ! – eugeneK Apr 27 '17 at 15:54
  • 8
    Thanks. I had my AddCors after UseMvc and that was causing it to not work properly. Yours is the only answer that mentions this. – JesseNewman19 May 25 '17 at 19:44
  • 4
    This doesn't work I don't think. When supplying credentials, you can't allow any origin. I'm still trying to get this to work. – Jason Goemaat Oct 07 '17 at 04:31
  • 12
    That's the key piece: `.UseCors()` before `.UseMvc()` – Francis Nepomuceno Oct 22 '17 at 23:15
  • 3
    Wasted time with not knowing about UseCors before UserMvc... thanks for the help! – Thomas Nov 21 '18 at 21:56
  • 2
    @JasonGoemaat As of .NET Core 2.2 you cannot use both `AllowAnyOrigin` and`AllowCredentials`: https://github.com/aspnet/AspNetCore/issues/3106 - you may only use one or the other. – Ian Kemp Oct 22 '19 at 05:57
  • 1
    Nothing is working, i tried all options and it's still being blocked by CORS. If i call my own server at localhost, it gets the value. – Ali123 May 11 '20 at 19:46
  • Is this solution only for Web API or does it also work with MVC? – Ali123 May 11 '20 at 20:00
  • @Ali123 I can't test this right now but this used to be the solution for ASP.NET Core 1 and 2 versions (It's clearly mentioned in the answer) – Vahid Amiri May 13 '20 at 07:45
  • 1
    In my case I was not using .UseMvc() but .UseRouting() and I have had to add app.UseCors("AllowAll"); AFTER the .UseRouting(). – Sergio Prats Apr 07 '21 at 21:35
51

Based on Henk's answer I have been able to come up with the specific domain, the method I want to allow and also the header I want to enable CORS for:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
         options.AddPolicy("AllowSpecific", p => p.WithOrigins("http://localhost:1233")
                                                   .WithMethods("GET")
                                                   .WithHeaders("name")));
    services.AddMvc();
}

usage:

[EnableCors("AllowSpecific")]
Oluwafemi
  • 14,243
  • 11
  • 43
  • 59
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – zrvan Aug 11 '15 at 14:06
  • 16
    `To critique or request clarification from an author` I don't think that's the case here and Henk's answer have been marked already. My answer was an add-on if you want to allow specific domains. – Oluwafemi Aug 11 '15 at 14:17
  • Something is missing in your code, 'IServiceCollection' does not contain a definition for 'ConfigureCors'. Please check it and try to give a complete answer. – Sami-L Apr 02 '18 at 17:04
  • @Sami-L Please check my updated answer. I found out that `ConfigureCors` was changed to `AddCors`. – Oluwafemi Apr 03 '18 at 07:25
  • 1
    this worked well for me for .netcoreapp2.2 – tcables Oct 28 '22 at 13:22
47

Got this working with .NET Core 3.1 as follows

  1. Make sure you place the UseCors code between app.UseRouting(); and app.UseAuthentication();
app.UseHttpsRedirection();

app.UseRouting();
app.UseCors("CorsApi");

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints => {
    endpoints.MapControllers();
});
  1. Then place this code in the ConfigureServices method
services.AddCors(options =>
{
    options.AddPolicy("CorsApi",
        builder => builder.WithOrigins("http://localhost:4200", "http://mywebsite.com")
            .AllowAnyHeader()
            .AllowAnyMethod());
});
  1. And above the base controller I placed this
[EnableCors("CorsApi")]
[Route("api/[controller]")]
[ApiController]
public class BaseController : ControllerBase

Now all my controllers will inherit from the BaseController and will have CORS enabled

phoenix
  • 7,988
  • 6
  • 39
  • 45
tfa
  • 1,643
  • 16
  • 18
  • 8
    Things werent working for me until I `place the UseCors code between app.UseRouting(); and app.UseAuthentication();` – 0014 Jun 25 '20 at 04:13
  • 3
    Nobody mentioned except @tfa that position of the UseCors code must be between app.UseRouting(); and app.UseAuthentication(); It's matter! – Branislav Nov 05 '20 at 17:12
  • 2
    CORS didn't work for me until I got to know that the order of calls matters. Thanks! – JohnyL Dec 20 '20 at 12:56
  • 1
    Do I still need to add the attribute if I use the default policy? FYI, I have tested as `[EnableCors]` and in .Net 5. – Hamid Mayeli Jan 03 '21 at 00:41
  • @0014 - thank you so much, you're the only one that even helped at all getting this to work for me. These required order method calls seem pretty bad design. I understand why they work that way, but damn does it suck. – peaceoutside Feb 10 '21 at 21:36
  • thanks for saving time. The only full answer here. – Alex Sham Sep 22 '21 at 21:46
  • love how everybody says something else about where to place .UseCors() – kewur Oct 02 '22 at 10:15
17

Specifically in dotnet core 2.2 with SignalR you must change

.WithOrigins("http://localhost:3000") or

.SetIsOriginAllowed(isOriginAllowed: _ => true) //for all origins

instead .AllowAnyOrigin() with .AllowCredentials()

https://trailheadtechnology.com/breaking-change-in-aspnetcore-2-2-for-signalr-and-cors/

https://github.com/aspnet/AspNetCore/issues/4483

PJ3
  • 3,870
  • 1
  • 30
  • 34
  • Using SignalR in a .NET Core console app and this is the only working solution for my scenario. – asdf Oct 02 '19 at 11:48
14

If you are hosting on IIS, one possible reason is you are getting this is because IIS is blocking OPTIONS verb. I spent almost an hour because of this:

One telltale indication is you are getting 404 error during OPTIONS request.

To fix this, you need to explicitly tell IIS not to block OPTIONS request.

Go to Request Filtering:

IIS Request Filtering

Make sure OPTIONS is allowed:

Make sure OPTIONS is True

Or, just create a web.config with the following setting:

<system.webServer>
    <security>
        <requestFiltering>
            <verbs>
                <remove verb="OPTIONS" />
                <add verb="OPTIONS" allowed="true" />
            </verbs>
        </requestFiltering>
    </security>
</system.webServer>
Rosdi Kasim
  • 24,267
  • 23
  • 130
  • 154
  • 1
    Thanks a lot for this. I tried everything on https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors-with-endpoint-routing and yet i was getting only CORS errors. Until somebody pointed out your answer... I wonder why the people at MS didn´t care to include this little tip on their guide. – SonMauri Aug 18 '20 at 15:50
10

you have three ways to enable CORS:

  • In middleware using a named policy or default policy.
  • Using endpoint routing.
  • With the [EnableCors] attribute.

Enable CORS with named policy:

public class Startup
{
    readonly string CorsPolicy = "_corsPolicy";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                              builder =>
                              {
                                 builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                              });
        });

        // services.AddResponseCaching();
        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors(CorsPolicy);

        // app.UseResponseCaching();

        app.UseAuthorization();

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

UseCors must be called before UseResponseCaching when using UseResponseCaching.

Enable CORS with default policy:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddDefaultPolicy(
                builder =>
                {
                     builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

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

Enable CORS with endpoint

public class Startup
{
    readonly string CorsPolicy = "_corsPolicy ";

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy(name: CorsPolicy,
                              builder =>
                              {
                                  builder.AllowAnyOrigin()
                                      .AllowAnyMethod()
                                      .AllowAnyHeader()
                                      .AllowCredentials();
                              });
        });

        services.AddControllers();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseRouting();

        app.UseCors();

        app.UseAuthorization();

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

Enable CORS with attributes

you have tow option

  • [EnableCors] specifies the default policy.
  • [EnableCors("{Policy String}")] specifies a named policy.
Reza Jenabi
  • 3,884
  • 1
  • 29
  • 34
  • It sucks you can't configure CORS without compiling. If your client changes it's address, you have to go through a rebuild process and redeployment. MS didn't think too hard about this. – ATL_DEV Oct 27 '21 at 18:53
  • 1
    I have done all the code you listed here for the "default policy" on my web mvc and api projects - all running on localhost and still get a CORS error calling the api from the mvc app – PandaWood Mar 30 '22 at 02:42
  • I also added the `[EnableCors]` attribute on the offending API call, I still get a CORS error, there must be something else at play here – PandaWood Mar 30 '22 at 02:48
  • Same here. Nothing in this page works. Unbelievable!!! – Gabriel Anderson Oct 11 '22 at 21:46
9

You have to configure in Startup.cs class

services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials());
        });
nPcomp
  • 8,637
  • 2
  • 54
  • 49
SUNIL DHAPPADHULE
  • 2,755
  • 17
  • 32
6
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("AllowAnyOrigin",
            builder => builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());
    });

    services.Configure<MvcOptions>(options => {
        options.Filters.Add(new CorsAuthorizationFilterFactory("AllowAnyOrigin"));
    });            
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Nathan Alard
  • 1,753
  • 17
  • 9
  • 1
    Wonderful way to circumvent the already deployed browser security. Just don't! – JCKödel Jan 17 '18 at 17:50
  • 4
    I don't think this should be down-voted. This is an "alternate" way. You can either use the "UseCors()" method or else add a global MVC filter like what Nathan did here. – Josh Mouch May 03 '18 at 13:38
  • this works for me on .net core 2.2 plus adding app.UseCors("AllowAnyOrigin"); in "Configure" method – Harry Sarshogh Feb 08 '19 at 17:19
  • It's important to "Add Microsoft.AspNetCore.Cors nuget package to your project". Thank you for mention it! – Mason Zhang Nov 21 '19 at 15:05
  • @JoshMouch for every serious project there's a guy with 5 users in an office who just need their local-hosted, internal-network API to work *now* without giving a hoot about CORS – PandaWood Mar 30 '22 at 05:29
5

For Web API(ASP.Net core 6.0) In Program.cs just add before builder.Build();

builder.Services.AddCors(p => p.AddPolicy("corsapp", builder =>
{
    builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader();
}));

also add

app.UseCors("corsapp");
3

For ASP.NET Core Web API 5

In ConfigureServices add services.AddCors(); Before services.AddControllers();

Add UseCors in Configure

app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
2

In case you get the error "No 'Access-Control-Allow-Origin' header is present on the requested resource." Specifically for PUT and DELETE requests, you could try to disable WebDAV on IIS.

Apparently, the WebDAVModule is enabled by default and is disabling PUT and DELETE requests by default.

To disable the WebDAVModule, add this to your web.config:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="false">
    <remove name="WebDAVModule" />
  </modules>
</system.webServer>
Pang
  • 9,564
  • 146
  • 81
  • 122
Rik D
  • 128
  • 2
  • 11
1

All the workaround mentioned above may work or may not work, in most cases it will not work. I have given the solution here

Currently I am working on Angular and Web API(.net Core) and came across CORS issue explained below

The solution provided above will always work. With 'OPTIONS' request it is really necessary to enable 'Anonymous Authentication'. With the solution mentioned here you don't have to do all the steps mentioned above, like IIS settings.

Anyways someone marked my above post as duplicate with this post, but I can see that this post is only to enable CORS in ASP.net Core, but my post is related to, Enabling and implementing CORS in ASP.net Core and Angular.

1

Simple solution

DEVELOPMENT MODE ONLY!

if (app.Environment.IsDevelopment())
{
    app.UseCors(p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
}
FabioStein
  • 750
  • 7
  • 23
0

Step 1: We need Microsoft.AspNetCore.Cors package in our project. For installing go to Tools -> NuGet Package Manager -> Manage NuGet Packages for Solution. Search for Microsoft.AspNetCore.Cors and install the package.

Step 2: We need to inject CORS into the container so that it can be used by the application. In Startup.cs class, let’s go to the ConfigureServices method and register CORS.

enter image description here

So, in our server app, let’s go to Controllers -> HomeController.cs and add the EnableCors decorator to the Index method (Or your specific controller and action):

enter image description here

For More Detail Click Here

shebin c babu
  • 1,069
  • 8
  • 7
  • hey shebin, would you mind updating the URL to your blog which appears broken and inlining the code as text instead of pictures of text? – KyleMit Jul 16 '21 at 15:55
0

Some troubleshooting tips, after I managed to waste two hours on the most trivial CORS issue:

  1. If you see CORS policy execution failed logged... Don't assume that your CORS policy is not executing properly. In fact, the CORS middleware works, and your policy is executing properly. The only thing this badly worded message means is that the request's origin doesn't match any of the allowed origins (see source), i.e. the request is disallowed.

  2. The origin check (as of ASP.NET Core 5.0) happens in a very simple way... i.e. case-sensitive ordinal string comparison (see source) between the strings you provided via WithOrigins() and what exists in HttpContext.Request.Headers[Origin].

  3. CORS can fail if you set an allowed origin with a trailing slash /, or if it contains uppercase letters. (In my case I did in fact accidentally copy the host with a trailing slash.)

Leaky
  • 3,088
  • 2
  • 26
  • 35
0

This Cover each endpoint . if you want block some endpoint use this annotation [DisableCors]
it well described here.
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0

  1. Add app.usecors(policyName) Between app.authentication() and app.routing() If you are using app.usMvc() above it.Inside the Configure Method.

  2. Inside the configureService Method

services.AddCors(options => options.AddPolicy(name: mypolicy,     builder =>     { builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin(); }));
  1. In Each controller add [EnableCors("mypolicy")]
        [EnableCors("mypolicy")] 
        [Route("api/[controller]")] [ApiController] 
        public class MyController : ControllerBase


eg:-

  namespace CompanyApi2
        {
            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(name: mypolicy,
                            builder =>
                            {
                                builder.AllowAnyHeader().AllowAnyMethod()
                                    .AllowAnyOrigin();
                            })); //add this
                    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
                    services.AddScoped<IDatarepository, DatabaseRepository>();
                }
        
                public string mypolicy = "mypolicy";
        
                // 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.UseHsts();
                    }
        
                    app.UseCors(mypolicy); //add this
                    app.UseHttpsRedirection();
                    app.UseMvc();
                }
            }
        }
lava
  • 6,020
  • 2
  • 31
  • 28
0

Lately when hosting the web app server on azure web app, had to edit azure app cors settings to resolve the matter (code only did not solve the issue)

  1. Less secured - Enable Access-Control-Allow-Credentials -leave it blank and add * as an allowed origin
  2. Mark Enable Access-Control-Allow-Credentials and then add the domains you want to allow the requests from
Luba Karpenko
  • 101
  • 2
  • 6
0

Got this working with .Net Core 3.1 as follows:

In ConfigureServices() method:

 public void ConfigureServices(IServiceCollection services)
  {
   ...
   services.AddCors();
   ...
  }

In Configure() method:

 public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
   ...
   app.UseCors(builder =>
          builder.AllowAnyOrigin()
          .AllowAnyHeader()
          .AllowAnyMethod()
        );
   ...
  }
Salahuddin Ahmed
  • 4,854
  • 4
  • 14
  • 35
0

for .Net CORE 3.1 use:

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())
Elvis Skensberg
  • 151
  • 1
  • 9
0

pay attantion that "/" in the end - will block the CORS origin

builder.WithOrigins("http://example.com/","http://localhost:55233/");

will block

use

builder.WithOrigins("http://example.com","http://localhost:55233"); 
Citizen-Dror
  • 843
  • 9
  • 17
0

For "C# - ASP Net Core Web API (Net Core 3.1 LTS)", it worked for me ...

In Startup.cs file:

Inside "ConfigureServices" function add this code:

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

Note: In case of "CorsPolicy" you can change for what you like or use global variable in "Startup" class.

Inside "Configure" function add this code:

app.UseCors("CorsPolicy");

Check the call order of the functions, it should look like this:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}

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

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

And finally in your controller class add this code above your functions http:

[EnableCors("CorsPolicy")]

For example:

[EnableCors("CorsPolicy")]
[HttpPost("UserLoginWithGoogle")]
public async Task<ActionResult<Result>> UserLoginWithGoogle([FromBody] TokenUser tokenUser)
{            
    Result result = await usersGoogleHW.UserLoginWithGoogle(tokenUser.Token);
    return new JsonResult(result);
}

Note: "CorsPolicy" must match in the Startup and Controller.

Good luck ...

Arturo
  • 1
  • 2
-2

Install nuget package Microsoft.AspNetCore.CORS

In Startup.cs under ConfigureServices method add the following code before services.AddMVC()

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

In Startup.cs inside the Configure method add app.UseCors("AllowMyOrigin"); before you call app.UseMvc()

Note that when sending a request from client side remember to use https instead of http.

Ade Stringer
  • 2,611
  • 17
  • 28