SignalR push notifications to all browser instances of single authenticated user

后端 未结 1 1333
猫巷女王i
猫巷女王i 2021-02-04 15:15

I\'m working on an application that needs to notify the user when they receive a new notification. The application will be hosted on Azure and will be .NET MVC 3 (probably not

1条回答
  •  离开以前
    2021-02-04 15:51

    Your call to make a Group with the User Name as a key is good one and I think it's the most fast to implement. You can call a function every time a page loads(and ConnectionId is changed) by subscribing to the:

    $.connection.hub.start(function () {
        yourHub.register();
    });
    

    And in the hub in Code behind:

    public void Register()
    {
        AddToGroup(username);
    }
    

    And when you want to refresh the client's screens you do:

    Clients[username].refreshClientScreen();
    

    Where refreshClientScreen() is your javascript function which does the job of hiding the notification in the browser.

    Another way to do it is to check the ConnectionId on every request and have a place where you register and persist the user's connections on the server. When you need to update them you can use this code on each one of them:

    Clients[ConnectionId].refreshClientScreen();
    

    You can find the ConnectionId in the Context object of a Hub.

    I think the second approach is harder to implement because you have to manage where you'd save the ConnectionId-s and subscribe to the Disconnect event by implementing IDisconnect so you can keep your ConnectionId-s list up to date, so I'd choose the first approach - the one with the groups.

    0 讨论(0)
提交回复
热议问题