Home > Mobile >  .NET 6 Web Api Project No 'Access-Control-Allow-Origin' header is present on the requested
.NET 6 Web Api Project No 'Access-Control-Allow-Origin' header is present on the requested

Time:06-08

I have a simple javascript app calling a .NET 6 Web API

In the program.cs file, I have added builder.Services.AddCors and app.UseCors as below.

But I still get CORS error when making a POST Request:

Access to XMLHttpRequest at 'http://192.168.2.157:81/Controller/MyMethod' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

My CORS config:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "AllowAll",
                      policy =>
                      {
                          policy.AllowAnyOrigin();
                          policy.AllowAnyMethod();
                          policy.AllowAnyHeader();
                      });
});

// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseSwagger();
app.UseSwaggerUI();

app.UseCors("AllowAll");
//app.UseAuthorization();
app.MapControllers();

app.Run();

I've also tried to enable it inside the appsetting (Both for the default and development file):

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "cors": {
    "rules": [
      {
        "origin": "*",
        "allow": true
      }
    ]
  }
}

Any idea why i'm not able to enable the CORS policy?

i'm publishing in a docker container and everything works if i run it locally, if it's of any help

CodePudding user response:

Thanks to @TinyWang :

I added

<DockerfileRunArguments>-e "ENABLE_CORS=true" -p 81:80</DockerfileRunArguments>

inside of my .csproj.

Now i'm able to call my web server (192.168.2.157:81) form my client (127.0.0.1)

  • Related