Reputation: 67
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:
Putting app.UseCors("Epicerie"); after UseRouting
Try to use this: [EnableCors("Epicerie")] instead of app.UseCors("Epicerie");
This also didn't work:
builder.Services.AddCors(o => o.AddPolicy("Epicerie", builder => { builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader(); }));
Please, I do not know what I can do AT ALL.
Maybe I miss something... but what? :)
Upvotes: 0
Views: 267
Reputation: 1339
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.
Enable CORS in the Azure App Service as follows:
Output:
Upvotes: 0