Search code examples
c#asp.netsignalr-hub

store data in asp.net with signalr


I am trying to store data in asp.net application with signalr. To ilustrate my problem here is example.

I have a hub that informs controll that user has connected and sends his id.

public static event EventHandler<IdEventArgs> userConnected;

public void Connected()
{
    Debug.WriteLine("Hub Connected Method");
    var id = Context.ConnectionId;

    userConnected(this, new IdEventArgs(id));
}

Then I have my controller that adds event handler to hub

    public ActionResult Index()
    {
        LoadingHub.userConnected += new EventHandler<IdEventArgs>(UserConnected);

        return View();
    }

And finally my method that should save the obtained data

    private void UserConnected(object sender, IdEventArgs e)
    {
        Debug.WriteLine("User Connected with Id: " + e.Id);

        //To do:
        //save data
    }

I tryed saving to Session but Session object is null here. I came across user profiles and maybe this would be a good solution - is it possible to create new profile when user connects to store data inside, and when he disconects to destroy said profile? Or maybe completly diffrent approach is more siutable here?


Solution

  • As already mentioned in comments, Session is not available with SignalR. I'd say you have 2 main options:

    • use the state feature, as explained here, this way your data will go back and forth over the connection but you'll have it around as long as the connection is alive (ideal for small payloads and if you don't mind clients accessing that info)
    • use dependency injection (check here) to pass a service to your hub, whose interface you define as you will (it could be a trivial pair of get/set methods), and whose implementations could be many, from an in-memory static (not necessarily literally) dictionary for dev scenarios up to any kind of persistent store you want to use to provide horizontal scalability (if needed). It's a bit of effort at the beginning but then it gets very easy and flexible