Hi I'm using an angular app to connect to signalr, I am using "@aspnet/signalr": "1.0.0-preview1-final".
I need to send the connectionId to my controller (I need to do some process and tell all others clients but no the user making the request), the problem is Connection Id is private, there is a way to get the connection Id?
Each client connecting to a hub passes a unique connection id. You can retrieve this value in the Context. ConnectionId property of the hub context.
Microsoft's @aspnet/signalr package makes it possible to leverage both Azure and Angular to create applications that utilize SignalR.
We change the BroadcastChartData() method to accept connectionId as an additional parameter. This way, we can find the client using the connectionId and send a message just to that client. Additionally, we add a new GetConnectionId() method, which returns the connectionId of the client.
Seems like an XY problem.
Hub:
public async Task TellAllOtherClients(object[] args)
{
await Clients.Others.SendAsync("method", args);
}
connectionId
(solution Y)Hub:
public string GetConnectionId()
{
return Context.ConnectionId;
}
Client:
hub.invoke('getConnectionId')
.then(function (connectionId) {
// Send the connectionId to controller
});
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));
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With