Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a parameter to hub in SignalR?

My code in SignalR hub:

public class AlertHub : Hub
{
    public static readonly System.Timers.Timer _Timer = new System.Timers.Timer();

    static AlertHub()
    {
        _Timer.Interval = 60000;
        _Timer.Elapsed += TimerElapsed;
        _Timer.Start();
    }

    static void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        //Random rnd = new Random();
        //int i = rnd.Next(0,2);
        Alert alert = new Alert();
        i = alert.CheckForNewAlerts(EmpId);

        var hub = GlobalHost.ConnectionManager.GetHubContext("AlertHub");

        hub.Clients.All.Alert(i);
    }
}

Somehow I need to pass EmpId parameter. How to accomplish this?

Some more client details: On my aspx page I have the following code:

<script type="text/javascript">

    $(function () {
        var alert = $.connection.alertHub;
        alert.client.Alert = function (msg) {
            if (msg == 1) {
                $("#HyperLink1").show();
                $("#HyperLink2").hide();

            }
            else {
                $("#HyperLink1").hide();
                $("#HyperLink2").show();
            }
            //$("#logUl").append("<li>" + msg + "</li>");
        };
        $.connection.hub.start();
    });

</script>

On ASPX page, my EmpID is in the session object and I need to somehow use it in the SignalR hub.

like image 292
WinFXGuy Avatar asked Jan 12 '23 02:01

WinFXGuy


1 Answers

In addition to the accepted answer I have used this to pass multiple query strings from client to hub: In Client:

Dictionary<string, string> queryString = new Dictionary<string, string>();
        queryString.Add("key1", "value1");
        queryString.Add("key2", "value2");
        hubConnection = new HubConnection("http://localhost:49493/signalr/hubs", queryString);

---Rest of the code--------

In Hub class:

public override Task OnConnected()
{
 var value1 = Convert.ToString(Context.QueryString["key1"]);
 var value2 = Convert.ToString(Context.QueryString["key2"]);
 return base.OnConnected();
}

I am using the “Microsoft.AspNet.SignalR.Client” library of version “2.3.0.0” in a windows form application using c#.

like image 59
Sharad Verma Avatar answered Jan 22 '23 14:01

Sharad Verma