I have not found any direct way to call. So, we need to write our own logic inside a method provided by SignalR Library.
There is a Hub class provided by the SignalR library.
In this class, we have 2 methods.
- OnConnectedAsync()
- OnDisconnectedAsync(Exception exception)
In the same way, when any client gets disconnected, then the OnDisconnectedAsync method is called.
So, let us see it by example.
Step 1
Here, I am going to define a class SignalRHub and inherit the Hub class that provides virtual method and add the Context.ConnectionId: It is a unique id generated by the SignalR HubCallerContext class.
- public class SignalRHub : Hub
- {
- public override Task OnConnected()
- {
- ConnectedUser.Ids.Add(Context.ConnectionId);
- return base.OnConnected();
- }
- public override Task OnDisconnected()
- {
- ConnectedUser.Ids.Remove(Context.ConnectionId);
- return base.OnDisconnected();
- }
- }
In this step, we need to define our class ConnectedUser with property Id that is used to Add/Remove when any client gets connected or disconnected.
Let us see this with an example.
Now, you will get the result of currently connected client using ConnectedUser.Ids.Count.
- public static class ConnectedUser
- {
- public static List<string> Ids = new List<string>();
- }
Note
As you see, here I am using a static class that will work fine when you have only one server, but when you will work on multiple servers, then it will not work as expected. In this case, you could use a cache server like Redis cache, SQL cache.

Mateus VasconcelosPosted Sep 21, 2021, 12:12 PM
The line 05 and 10 on SignalRHub are not thread safe. And this article is not up to date with newer versions of SignalR. =(