Get SignalrR ConnectionId on ClientSide (Angular App)
From Javascript...
Just interrogate the connection id property of the SignalR connection once a connection is made (in the start().done
function). Like this:
var connectionid = _signalconnection.connection.connectionId;
Just be sure to do this in both the start().done
and the onreconnected
event.
That allows you to get the updated connectionid if it changes on a reconnect.
Pretty straightforward.
Here's my connection start statement, in case it helps...
_signalconnection.start().then(function ()
{
console.log("Setup_SignalR: connection open.");
// Get the connectionID...
_connectionid = _signalconnection.connection.connectionId;
// Make a log entry that is page contextual...
var page = window.location.pathname;
console.log("Setup_SignalR:ConnectionOpen for page (" + page + ") with connectionID = " + _connectionid);
}).catch(function (err)
{
console.error("Setup_SignalR: connection failed. err = " + err);
});
Client:
let connection: signalR.HubConnection;
let accessToken = "3076a225-f2f6-4c68-b894-08accb62bb90";
connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:8178/notifyHub", { accessTokenFactory: () => accessToken }).build();
connection.start().then(function(){connection.invoke("GetConnectionId").then(function(connectionId){console.log(connectionId)})}).catch(err => console.error(err));
Seems like an XY problem.
Tell all other clients (problem X)
Hub:
public async Task TellAllOtherClients(object[] args)
{
await Clients.Others.SendAsync("method", args);
}
Get connectionId
(solution Y)
Hub:
public string GetConnectionId()
{
return Context.ConnectionId;
}
Client:
hub.invoke('getConnectionId')
.then(function (connectionId) {
// Send the connectionId to controller
});