I am building a small app with Angular 19 and .NET 9 and I have the following issue with CORS:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7002/hubs/communication/negotiate?negotiateVersion=1. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 307.
I tried out many different solutions from many posts here on stackoverflow and official Microsoft docs (posts are probably a bit old since they're using .NET 7 and Angular 2.2).
My frontend side SignalR client has the following code to connect to the backend:
private startConnection()
{
this.hubConnection = new HubConnectionBuilder()
.withUrl('http://localhost:7002/hubs/communication')
.withAutomaticReconnect([100, 200, 500, 1000, 2000, 3000, 5000])
.build();
this.hubConnection
.start()
.then(() => console.log('Connection to Communication Hub succesful!'))
.catch(err => console.log('Error establishing connection to Communication Hub: ' + err));
}
And in my backend side, the code in program.cs
I have right now is as follows:
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", policy => policy.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials());
});
var webSocketOptions = new WebSocketOptions
{
KeepAliveInterval = TimeSpan.FromMinutes(2)
};
webSocketOptions.AllowedOrigins.Add("http://localhost:4200");
// Code omitted for brevity
app.MapHub<CommunicationHub>("/hubs/communication");
app.UseCors("CorsPolicy");
app.UseWebSockets(webSocketOptions);
UPDATE: After JasonPan suggested to change the order I now have it like this:
app.UseCors("CorsPolicy");
app.UseWebSockets(webSocketOptions);
app.MapHub<CommunicationHub>("/hubs/communication");
What am I doing wrong? Any help will be much appreciated : ).
UPDATE2: Here's a little sample project with the issue: https://gitlab.com/arendevel/corsissue
Thanks to @Brennan and @JasonPan I could find that the problem was connecting to the http port on backend from the frontend and having https redirection. Connecting directly to the https port solved it for me.