Search code examples
asp.net-mvcasp.net-mvc-4signalrsignalr-hub

signalR passing objects to hub


I need to be able to somehow associate List<string> (that gets loaded in my controller) with a connectionId that is generated in the HUB.

In my MVC app I have an Action that fills List<string> with some data. After the page is loaded, OnConnected method is executed in my Hub where a new ConnectionId is generated. I would like to associate that ConnectionIdwith myList<string>.

Since OnConnected is executed after the action completes I don't believe there's another way of doing it. Is there?

How would I pass a List (or some other object) to my hub so that is associated with a specific ConnectionId?

thanks


Solution

  • Instead of passing data to your hub, take in data from your hub.

    So for instance you can use static dictionaries/lists to have the two reference eachother:

    public class MyHub : Hub
    {
        public override OnConnected()
        {
            MyController.Associate(Context.ConnectionId);
        }
    }
    
    public class MyController
    {
        public static ConcurrentDictionary<string, List<string>> cidToList = new ConcurrentDictionary<string, List<string>>();
        public static List<string> mylist = new List<string>();
    
        public static void Associate(string cid)
        {
            cidToList.TryAdd(cid, mylist);
        }
    }