Travis Pettry
Travis Pettry

Reputation: 1352

.Net 5 Web API CORS LocalHost

I am building a .Net 5 Web API and I am having issues with CORS only when I am running locally (aka localhost). When I have deployed my app to Azure I can access my API just fine from my Blazor app.

Class Startup.cs

readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

Class: Startup.cs
Method: ConfigureServices

services.AddCors(options =>
{
    //didn't work
    //options.AddDefaultPolicy(builder =>
    //{
    //    builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
    //});

    options.AddPolicy(name: MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("https://localhost:44373/", "https://myawesomesite")
                          .AllowAnyMethod()
                          .AllowAnyHeader()
                          .AllowCredentials();
                      });
}); 

Class: Startup.cs
Method: Configure

app.UseCors(MyAllowSpecificOrigins);

Upvotes: 3

Views: 9434

Answers (2)

Serge
Serge

Reputation: 43910

Just remove trailing "/" from your local host url and for the test you can try to remove .AllowCredentials().

And use this syntax:

services.AddCors(o => o.AddPolicy(MyAllowSpecificOrigins,
                      builder =>
                      {
                          builder.WithOrigins("https://localhost:44373", 
                              "https://myawesomesite")
                          .AllowAnyMethod()
                          .AllowAnyHeader();
                      }));

and your UseCors method should be between UseRouting and UseAuthourization


app.UseRouting()
....
.....
app.UseCors(MyAllowSpecificOrigins);

....
....
app.UseAuthorization(); // if you need the one

Upvotes: 10

Bilal Mehrban
Bilal Mehrban

Reputation: 637

What I have on my side working properly as below.

Class: Startup.cs

Method: ConfigureServices

services.AddCors(c =>  
  { 
    c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());  
  }); 

Class: Startup.cs

Method: Configure

app.UseCors(options => options.AllowAnyOrigin());

Try this, let me know if it helps.

Upvotes: 2

Related Questions