Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Context is null in SignalR hub

I have a Web Forms application and testing to see how SignalR works for one of my requirement. My hub code:

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace SignalRTest.Hubs
{
    public class NotificationHub : Hub
    {
        public static readonly System.Timers.Timer _Timer = new System.Timers.Timer();


        public NotificationHub()
        {
            var myInfo = Context.QueryString["myInfo"];

            _Timer.Interval = 2000;
            _Timer.Elapsed += TimerElapsed;
            _Timer.Start();
        }

        void TimerElapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            Random rnd = new Random();
            int i = rnd.Next(0, 2);
            var hub = GlobalHost.ConnectionManager.GetHubContext("NotificationHub");
            hub.Clients.All.Alert(i);
        }
    }
}

My Client call:

<script type="text/javascript">
    $(function () {
        var logger = $.connection.notificationHub;
        logger.client.Alert = function (msg) {
            if (msg == 1) {
                $("#HyperLink1").show();
                $("#HyperLink2").hide();

            }
            else {
                $("#HyperLink1").hide();
                $("#HyperLink2").show();
            }
        };

        $.connection.hub.qs = "myInfo=12345";
        $.connection.hub.start();
    });
</script>

But, for some reason, when examined the Context on the server code (in hub), it is null, so I cannot retrieve the querystring value. Any ideas?

like image 507
WinFXGuy Avatar asked Mar 20 '23 08:03

WinFXGuy


1 Answers

I don't believe the Context is available at the point the Hub is created. Instead you can override OnConnection on your Hub class:

public override Task OnConnected()
{
    var myInfo = Context.QueryString["myInfo"];

    return base.OnConnected();
}

Docs on Hub Object Lifetime:

You don't instantiate the Hub class or call its methods from your own code on the server; all that is done for you by the SignalR Hubs pipeline. SignalR creates a new instance of your Hub class each time it needs to handle a Hub operation such as when a client connects, disconnects, or makes a method call to the server.

Because instances of the Hub class are transient, you can't use them to maintain state from one method call to the next. Each time the server receives a method call from a client, a new instance of your Hub class processes the message. To maintain state through multiple connections and method calls, use some other method such as a database, or a static variable on the Hub class, or a different class that does not derive from Hub. If you persist data in memory, using a method such as a static variable on the Hub class, the data will be lost when the app domain recycles.

like image 140
Ben Foster Avatar answered Mar 22 '23 21:03

Ben Foster