Reputation: 51
I am consistently getting CORS issues when I attempt to hit my ASP.NET Core API SignalR endpoint. I believe I have it configured to allows all Headers, Method, when the origin is my localhost.
var builder = WebApplication.CreateBuilder(args);
// 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();
// Services
// Hubs
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors(builder =>
{
builder
.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
app.UseHttpsRedirection();
app.MapControllers();
app.UseRouting();
app.UseAuthorization();
app.MapHub<ChessHub>("/hubs/chess");
app.Run();
Upvotes: 0
Views: 301
Reputation: 99
app.UseCors(), Should be between app.UseRouting() and app.UseAuthentication(); Also, you have not added AddCors Service.
builder.Services.AddCors()
Try the below Code.
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddCors();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Services
// Hubs
builder.Services.AddSignalR();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.MapControllers();
app.UseRouting();
app.UseCors(builder =>
{
builder
.WithOrigins("http://localhost:3000")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
app.UseAuthentication();
app.UseAuthorization();
app.MapHub<ChessHub>("/hubs/chess");
app.Run();
Upvotes: 2