mathdx
mathdx

Reputation: 67

Error .net 6 cors policy "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

This is my Program.cs:

...

builder.Services.AddCors(o => o.AddPolicy("Epicerie", builder =>
{
    builder
        .WithOrigins("https://epicerieclient20231122200526.azurewebsites.net")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
}));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseCors("Epicerie");
app.UseRouting();

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

app.MapControllers();

app.Run();

I got this error when I deployed my api and client on Azure:

Access to fetch at '{mybaseurlapi}/api/Comptes/Connexion' from origin '{mybaseurlclient}' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have tried many things:

Please, I do not know what I can do AT ALL.

Maybe I miss something... but what? :)

Upvotes: 0

Views: 267

Answers (1)

Pavan
Pavan

Reputation: 1339

  • Initially, I was also unable to deploy the API with my Visual Studio version 17.7.1. However, after upgrading the Visual Studio version to 17.8.1, I was able to deploy without any issues.

enter image description here

I have made some changes in your code, @mathdx.

Program.cs:

using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(options =>
{
    options.SwaggerDoc("v1", new OpenApiInfo
    {
        Title = "Safari Wave API",
        Version = "v1",
    });
});

builder.Services.AddCors(o => o.AddPolicy("Epicerie", builder =>
{
    builder
        .WithOrigins("https://epicerieclient20231122200526.azurewebsites.net/")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials();
}));
var app = builder.Build();
app.UseDeveloperExceptionPage();

app.UseSwagger();
app.UseSwaggerUI(options =>
{
    options.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API V1");

    if (app.Environment.IsDevelopment())
    {
        options.RoutePrefix = "swagger";
    }
    else
    {
        options.RoutePrefix = string.Empty;
    }
});
app.UseHttpsRedirection();
app.UseCors("Epicerie");
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();

The above code executed successfully in local. I am able to publish successfully onto the Azure portal.

enter image description here

Enable CORS in the Azure App Service as follows:

enter image description here

Output:

enter image description here

Upvotes: 0

Related Questions