Home > Enterprise >  How to resolve this CORS issue ? (.NET Web API)
How to resolve this CORS issue ? (.NET Web API)

Time:06-30

I have a .NET Core Web API running on http://localhost:5001. I am calling these service from another web app (Which is running on http://localhost:5004) and I got the error in browser:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5000/api (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 405.

I put below code in Startup.cs in Web API

    app.UseCors(
          options => options.WithOrigins("http://localhost:5004/", "https://localhost:5004/").AllowAnyMethod()
     );

This time also error occurred but code is 205.

Third time I ran with removing '/' in options:

app.UseCors(
      options => options.WithOrigins("http://localhost:5004", "https://localhost:5004").AllowAnyMethod()
 );

Error remains, but this time there was no status code.

CodePudding user response:

use this. you also have to put last condition. AllowAnyHeader.

  app.UseCors(
  options => options
                .WithOrigins("http://localhost:5004", "https://localhost:5004")
                .AllowAnyMethod().
                .AllowAnyHeader());

CodePudding user response:

Configuration in Startup.cs till .net Core 5. From 6 onwards in Program.cs

Add following in ConfigureServices

services.AddCors(options =>
        {
            options.AddDefaultPolicy(policy =>
            {
                policy.WithOrigins("https://localhost:5005",
                                    "https://localhost:5000",
                                    "https://localhost:3011",
                                    "http://localhost:3011")
                                    .AllowAnyHeader()
                                    .AllowAnyMethod();
            });
        });

add following in Configure

app.UseCors();

CodePudding user response:

If you have a look at the docs, all their examples are placing the rules in the AddCors method, not the UseCors method.

So instead of

app.UseCors(
  options => options.WithOrigins("http://localhost:5004", "https://localhost:5004").AllowAnyMethod()
 );

try the following

string myPolicy = "my_policy";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options=>{
    options.AddPolicy(myPolicy,policy=>{
        policy.WithOrigins("http://localhost:5004", "https://localhost:5004");
    });
});

builder.Services.AddRazorPages();

var app = builder.Build();

app.UseCors(myPolicy);
app.UseAuthorization();
app.MapRazorPages();

app.Run();
  • Related