Can't connect signalR client in angular 19 to signalR server in .Net 9

Discussão em 'Angular' iniciado por Aren Devel, Janeiro 21, 2025.

  1. Aren Devel

    Aren Devel Guest

    I am building an small app with Angular 19 and .NET 9 and I'm having 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 front-end side singlaR 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 on 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);


    What am I doing wrong? Any help will be much appreciated : ).

    Continue reading...

Compartilhe esta Página