For several days now, I've been trying to solve a CORS problem I'm having, however I already did a lot of attempts in the Program.cs
file to try to solve this but I can't figure this out.
Basically the CORS error only happens on POST
methods.
I have this code in Program.cs
:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddHttpClient();
builder.Services.AddCors(builder =>
{
builder.AddPolicy("AllowAll", options =>
{
options.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("AllowAll");
app.UseAuthorization();
app.MapControllers();
app.Run();
In the browser console I see this:
Access to XMLHttpRequest at 'https://localhost:7278/api/Topaz/SetTabletState' from origin 'https://example.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Can anyone help me figure this out?
I already tried to put the domain on the origins but still does not work.
I already tried to define the CORS policy in the controller but still does not work.
After systematic debugging, I conducted a test using XMLHttpRequest as an alternative to AJAX. Interestingly, I discovered that setting the "datatype" parameter to "jsonp" on AJAX effectively resolves the issue at hand. Notably, when employing XMLHttpRequest for making requests, no Cross-Origin Resource Sharing (CORS) errors were encountered.
Also, using XMLHttpRequest does not give me any CORS error and works as expected!