如何使用signalR c#MVC接收特定于用户的消息?

时间:2019-03-21 17:16:11

标签: c# asp.net-mvc signalr signalr.client

我有一个MVC应用程序。

我已经实现了singalR来接收实时通知,但是如何仅接收特定于用户的通知。

NotificationSend.cs

public class NotificationSend : Hub
{
    private static IHubContext hubContext = GlobalHost.ConnectionManager.GetHubContext<NotificationSend>();
    public static ConcurrentDictionary<string, MyUserType> MyUsers = new ConcurrentDictionary<string, MyUserType>();

    public override Task OnConnected()
    {
        MyUsers.TryAdd(Context.ConnectionId, new MyUserType() { ConnectionId = Context.ConnectionId });
        return base.OnConnected();
    }

    public override Task OnDisconnected(bool stopCalled)
    {
        MyUserType garbage;

        MyUsers.TryRemove(Context.ConnectionId, out garbage);

        return base.OnDisconnected(stopCalled);
    }

    public static void SendToUser(string messageText)
    {
        hubContext.Clients.Client(MyUsers.Keys.ToList().FirstOrDefault()).Notification(messageText);
    }

    public static void StopLoader(string messageText)
    {
        hubContext.Clients.Client(MyUsers.Keys.ToList().FirstOrDefault()).Stoploader(messageText);
    }
}
public class MyUserType
{
    public string ConnectionId { get; set; }
}

HomeController.cs

public class HomeController : Controller
    {

    public async Task<ActionResult> SaveData()
        {
         foreach (var mydata in DataList)
                {
                   // save data code and show below message on UI
                   NotificationSend.SendToUser(mydata.Name + ": Data saved");

我可以很好地在UI上收到通知,但问题是

  

如果用户A使用自己的计算机并登录,那么他应该只会收到他的通知,我知道webapp的网址是相同的。

为此,我进行了以下更改,但此更改后看不到任何通知。

string UserID = User.Identity.Name;
hubContext.Clients.User(UserID).Notification(mydata.Name + ": Data saved");

Layout.js

$(function () {
            var notification = $.connection.notificationSend;
            console.log(notification);
            notification.client.Notification = function (Count) {
                $('#liveupdate').empty();
                $('#liveupdate').show();
                $('#liveupdate').append(Count);
            };
            $.connection.hub.start().done(function () {
                var connectionId = $.connection.hub.id;
                console.log("Connected Successfully");
            }).fail(function (response) {
                console.log("not connected" + response);
            });
        });

2 个答案:

答案 0 :(得分:1)

这是我在VB.Net中的示例代码(您可以将其转换为C#):

Public Class SignalRHub
    Inherits Hub

    Private Shared hubContext As IHubContext = GlobalHost.ConnectionManager.GetHubContext(Of SignalRHub)()

    Public Sub SendToAll(ByVal msg As String)
        hubContext.Clients.All.addNewMessageToPage(msg)
    End Sub

    Public Shared Sub SendToUser(ByVal user As String, ByVal msg As String)
        hubContext.Clients.Group(user).addNewMessageToPage(msg)
    End Sub

    Public Overrides Function OnConnected() As Task
        Dim name As String = Context.User.Identity.Name
        Groups.Add(Context.ConnectionId, name)
        Return MyBase.OnConnected()
    End Function

End Class

您必须使用组。基本上我要做的是1个群组,供1个用户使用。通过用户名定义。

然后只需调用函数:

Dim user As User = idb.Users.Where(Function(a) a.id = userid).FirstOrDefault
Dim msg as string = "Any notification message"
SignalRHub.SendToUser(user.UserName, msg)

最后,使用JavaScript代码触发该事件:

var notification = $.connection.signalRHub;
notification.client.addNewMessageToPage = function (msg) {
    $("#notification").prepend(msg);
}

您要在其中放置通知消息的ID通知。

答案 1 :(得分:1)

添加一个静态类,其实例将被创建一次,并将像上下文实例一样将信息持久化在内存中

public static class NotificationsResourceHandler
{
    private static readonly IHubContext myContext;       
    public static Dictionary<string, string> Groups;



    static NotificationsResourceHandler()
    {
        myContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();   
        Groups = new Dictionary<string, string>();
    }

    public static void BroadcastNotification(dynamic model, NotificationType notificationType, string userName)
    {
        myContext.Clients.Group(userName).PushNotification(new { Data = model, Type = notificationType.ToString() });
    }
}

和在您的中心

[HubName("yourHub")]
public class MyHub : Hub
{
    public override Task OnConnected()
    {
        var userEmail = Context.QueryString["useremail"]?.ToLower();
        if (userEmail == null) throw new Exception("Unable to Connect to Signalr hub");

        if (NotificationsResourceHandler.Groups.All(x => x.Value != userEmail))
        {
            NotificationsResourceHandler.Groups.Add(Context.ConnectionId, userEmail);
            Groups.Add(Context.ConnectionId, userEmail);
        }
        return base.OnConnected();
    }

    public override Task OnDisconnected(bool stopCalled)
    {
        NotificationsResourceHandler.Groups.Remove(Context.ConnectionId);
        Clients.All.removeConnection(Context.ConnectionId);

        return base.OnDisconnected(stopCalled);
    }
}

通知将被推送到各个组,对于您的问题,您应该按照代码中的规定为每个用户创建一个单独的组。