Search code examples
c#asp.netsignalrsignalr-hubsignalr-2

How to set Application Variable in SignalR Hub class?


First of all I know that we can not access Session Variable and Application Variable in SignalR. But my requirement is I want to increase or decrease current logged in user count from SignalR OnConnect() and OnDisconnect() method. That I already did using below code.

SignalR Hub Class :-

public  class  SampleHub : Hub
{
     // Use this variable to track user count
     private  static  int _userCount = 0;

     // Public hub methods  
    :

     // Overridable hub methods  
     public  override Task OnConnected()
    {
       _userCount ++; // this I want to set in Application variable
    }
     public  override Task OnReconnected()
    {
        _userCount ++; // this I want to set in Application variable
    }
     public  override Task OnDisconnected(bool stopCalled)
    {
       _userCount --; // this I want to set in Application variable
    }
}

After setting values in _userCount variable When another user logged into the system. In Login button click event I want to check if _userCount >= 11 then show message

"YOU HAVE REACHED MAXIMUM CONCURRENT USER LOG IN LIMIT !"

But I am not able to use Application variable into SignalR - So My Question is How can I make access of _userCount variable in Login.aspx.cs or any other .aspx.cs page. Can I call any server method from SignalR Hub ?

any help will be greatly appreciated !

Thank You


Solution

  • Make your _userCount variable public and add reference of SampleHub class to Login.aspx.cs or any other cs page you want to and access your _userCount variable.

    public static int _userCount=0;
    

    On Login.aspx.cs page use it like this :

    int usercount = SampleHub._userCount;
    

    Hope this will help you