I have a simple webservice written in .NET Core 6 which is being accessed by a react application. Every call returns a CORS error: Access to XMLHttpRequest at 'https://localhost:7023/api/auth/login' from origin 'https://azmeits1:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Here is the code from Program.cs of the webservice:
builder.Services.AddDbContext<WpmDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
builder.Services.AddCors();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
//app.UseRouting();
app.UseHttpsRedirection();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.Run();
I know the order of events matter but no matter what I try I end up with the same CORS error in the deployment environment.
Ive tried swapping it around for:
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins, policy =>
{
policy
.SetIsOriginAllowed(origin => true)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
//app.UseRouting();
app.UseHttpsRedirection();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.Run();
Not sure if it makes a difference but the Controller code looks like this:
namespace TestAPI.Controllers
{
[Route("api/auth")]
[ApiController]
[Authorize]
public class AuthController : ControllerBase
{
[HttpPost("login")]
[AllowAnonymous]
public ActionResult<string> Login([FromBody] UserDto request)
{
//login code
}
}
}