- 
                Notifications
    You must be signed in to change notification settings 
- Fork 108
Description
Describe the bug
I have an Angular application that tries to subscribe messages to Azure Signal R Service via an ASP.Net api.
To Reproduce
When the page is loaded, a connection to SingalR event hub is made, which fails.
Exceptions (if any)
Further technical details
Log shown in Asp.net debug window, when the api is started: Remote Dependency telemetry event that records a successful WebSocket (SignalR) connection attempt from your application to Azure SignalR Service.
Application Insights Telemetry: {"name":"AppDependencies","time":"2025-06-04T19:28:19.4846701Z","iKey":"22eab917-eb83-40c4-aae7-bc6718ac1f42","tags":{"ai.application.ver":"1.0.0.0","ai.cloud.roleInstance":"DESKTOP-5VQOVDP","ai.operation.id":"103cba41b7d5caacf3b8a103c971d023","ai.internal.sdkVersion":"rdddsc:2.21.0-429","ai.internal.nodeName":"DESKTOP-5VQOVDP"},"data":{"baseType":"RemoteDependencyData","baseData":{"ver":2,"name":"GET /server/","id":"4630ed54bbfc733a","data":"wss://sit2-script-signalr.service.signalr.net:443/server/?hub=serversenteventshub&cid=17ef422f-1d77-49d0-885b-3c25f6675875","duration":"00:00:00.2562925","resultCode":"101","success":true,"type":"Http","target":"sit2-script-signalr.service.signalr.net","properties":{"ServiceOffering":"Supply Chain","UT Version":"1.2.1","ResponseBody":"�\u0002\u0003�","ResponseHeaders":"Server:nginx\r\nDate:Wed, 04 Jun 2025 19:28:20 GMT\r\nConnection:upgrade\r\nUpgrade:websocket\r\nSec-WebSocket-Accept:smi+3c5y3D/m/8AIoOLVgGACwGM=","_MS.ProcessedByMetricExtractors":"(Name:'Dependencies', Ver:'1.1')","ServiceLine":"DevX","RequestMethod":"GET","RequestPath":"GET:/server/","RequestHeaders":"Asrs-User-Agent:Microsoft.Azure.SignalR/1.30.3-rtm+2942484a7429fccf923214d0dbdd43f8166fdc75 (.NET 8.0.16; Microsoft Windows 10.0.26100; X64)\r\nX-ASRS-Server-Id:DESKTOP-5VQOVDP_09258f0330ee4681a971aa46e02f9a95\r\nX-Requested-With:XMLHttpRequest\r\nAuthorization:**\r\nConnection:Upgrade\r\nUpgrade:websocket\r\nSec-WebSocket-Key:hBuDN//h30WoVP8GvnCXLw==\r\nSec-WebSocket-Version:13\r\nRequest-Id:|103cba41b7d5caacf3b8a103c971d023.4630ed54bbfc733a.\r\ntraceparent:00-103cba41b7d5caacf3b8a103c971d023-4630ed54bbfc733a-00","AspNetCoreEnvironment":"Development","ComponentId":"0d1434fb-44c8-46d3-bce0-9727cc3411f2","DeveloperMode":"true","Environment":"Development","Correlation Id":"103cba41b7d5caacf3b8a103c971d023","Service":"Script","ComponentName":"Script Backend"}}}}
### Once the Page that is trying to initiate a signal R connection with backend is made, then Log shown in browser console
POST https://localhost:44329/events/negotiate?negotiateVersion=1
Respone 500 "Azure SignalR Service is not connected yet, please try again later."
### Logs in Asp.net Api Output window:
Failed to connect to '(Primary)https://sit2-script-signalr.service.signalr.net(hub=ServerSentEventsHub)', will retry after the back off period. Error detail: Unable to connect to the remote server. The base stream is not writeable. (Parameter 'stream'). Id: 2f08d135-b5e3-4d84-bf41-9e28c9b16db9
UI Code to initialize the SignalR connection
export class ServerSentEventsService {
    serverEvents: Subject<SSEEvent> = new Subject<SSEEvent>();
    lockEvents: Subject<SSEEvent> = new Subject<SSEEvent>();
    private endpoint: string;
    private projectId: string;
    private connectionId: string;
    private connection: any;
    constructor(private http: HttpClient, private msalService: MsalService, private appInsights: AppInsightsService) {
        this.endpoint = 'https://localhost:44329/events'; //Api url where events is the name of signalR hub.
    }
 public init(projectId: string) {
        // Establish connection with SginalR, if not `Connected` already.
        if (this?.connection?.state !== 'Connected') {
            this.connection = new signalR.HubConnectionBuilder()
                .withUrl(this.endpoint, {
                    accessTokenFactory: () => {
                        return this.getAuthorizationHeader();
                    }
                })
                .configureLogging(signalR.LogLevel.None)
                .withAutomaticReconnect([0, 3000, 5000, 10000, 15000, 30000])
                .build();
            this.connection.start()
                .then(() => {
                    this.subscribeToEvents(this.connection.connectionId, projectId);
                })
                .catch((e: any) => {
                    this.appInsights.trackExceptionAsEvent('SignalRFailedToNegotiate', e);
                    console.log(`Failed to subscribe ${projectId} events.`);
                });
        }
        else {
            this.subscribeToEvents(this.connection.connectionId, projectId);
        }
        this.connection.onreconnecting((error: any) => {
            this.appInsights.trackExceptionAsEvent('SignalRConnectionLost', error);
        });
        this.connection.onreconnected((connectionId: any) => {
            this.subscribeToEvents(connectionId, this.projectId);
        });
        this.connection.onclose((err: any) => {
            if (err) {
                console.log(`Connection Closed - ${err}`);
                this.appInsights.trackExceptionAsEvent('SignalROnCloseError', err);
            }
        });
        this.connection.on('newMessage', (message: any) => {
            console.log(`Received new event from server. - ${JSON.stringify(message)}`);
            message?.type === 'lock' ? this.lockEvents.next(message) : this.serverEvents.next(message);
        });
    }
private getAuthorizationHeader(): Promise<string> {
        const accessTokenRequest = {
            scopes: [AppConfig.backendScope]
        };
        return this.msalService.instance.acquireTokenSilent(accessTokenRequest).then(res => {
            return res.accessToken;
        });
    }
In Asp.net api startup.cs: In ConfigureServices() function below code is present.
 services.AddSignalR()
     .AddAzureSignalR(options =>
     {
         options.ServerStickyMode = ServerStickyMode.Required;
         options.ClaimsProvider = context =>context.User.Claims.Where(c=>c.Type == "name" || c.Type == "oid" || c.Type == "scp").ToList();
         options.Endpoints = new[]
         {
             new ServiceEndpoint(
            new Uri(@"https://sit2-script-signalr.service.signalr.net"),
                 new DefaultAzureCredential())
         };
        
     });
In Configure() below code is present:
 app.UseCors("AllowAllPolicy");
 app.UseRouting();
 
 app.UseAuthentication();
 app.UseEndpoints(endpoints =>
 {
     endpoints.MapHub<ServerSentEventsHub>("/events");  // Name of SignalR hub
     endpoints.MapControllers();
     endpoints.MapHealthChecks(Constants.HealthProbePath).WithMetadata(new AllowAnonymousAttribute());
 });
I have ensured that my user account in Visual Studio has Signal R App Server Owne Role for the Azure SignalR service.
- Your Azure SignalR SDK version :
- Your Server ASPNETCORE version or Assembly version of Microsoft.AspNetCore.SignalR: Microsoft.Azure.SingalR 1.10.3
- Your SignalR Client SDK version
Need help to troubleshoot this.