简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM