Error when try to connect to a hub by signalR

Viewed 220

I try to connect to a hub and get exception on call start();

Unhandled Exception: Exception: HttpConnection.stopConnection(Exception: WebSocket closed with status code: 1002 (null).) was called while the connection is still in the connecting state.

This is my sample code:

`notificationHubConnection = HubConnectionBuilder().withUrl('${AppAPI.apiNotificationHub}?access_token=$token').withAutomaticReconnect().build();

await notificationHubConnection!.start();`

Anyone has this problem ? Thank you very much !!!

1 Answers

You are missing the new keyword before the HubConnectionBuilder class. I believe this is causing your issue.

Try this:

  notificationHubConnection  = new HubConnectionBuilder()
  .withUrl(AppAPI.apiNotificationHub, {
    accessTokenFactory: () => token
  })
  .withAutomaticReconnect()
  .build();

  await notificationHubConnection.start();

NOTE:
I have used the access token factory to add the access token to the connection, but you can leave it hard coded in the query string if you'd like to.

(Using the access token factory will add the access token to the query string when using the websocket transport, but will add an authorization header when using the Server Sent Events or Long Polling transports. Hard coding the token in the query string will keep it in the query string regardless of the transport used).

If the error persists, perhaps you can make sure the URL you are using is correct?

Related