SignalR向特定客户端发送消息

6
我有一个带有静态方法的中心,可以向所有当前用户广播通知。
public class NotificationHub : Hub
{
    private static string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();

    [HubMethodName("sendNotifications")]
    public static void SendNotifications()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
        context.Clients.All.updateNotifications();
    }
}

我需要从前端JavaScript获取一些文本框输入,例如10038,这是用户ID,并将其发送到服务器类中。

public class NotificationRepository
{
    private readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    public IEnumerable<Notifications> GetNotifications(int userID)
    {
        var notifications = new List<Notifications>();

        using (var connection = new SqlConnection(_connString))
        {
            connection.Open();
            using (var command = new SqlCommand(String.Format(@"SELECT [ID], [UserID], [Message] FROM [dbo].[Notification] WHERE [UserID] = {0}", userID), connection))
            {
                command.Notification = null;

                var dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);

                if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }

                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    notifications.Add(item: new Notifications { ID = (int)reader["ID"], UserID = (int)reader["UserID"], Message = (string)reader["Message"] });
                }
            }
        }
        return notifications;
    }

    private void dependency_OnChange(object sender, SqlNotificationEventArgs e)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            NotificationHub.SendNotifications();
        }
    }
}

我会为特定用户返回一组通知,该用户由用户ID定义,但我似乎无法弄清楚如何映射响应,以便我只在signalR中向该特定客户返回通知。如何将客户的连接ID映射到输入的userID?我已经阅读了signalR文档,但它非常模糊,其他在线解决方案似乎没有解决这个特定问题。非常感谢任何帮助。
编辑: 到目前为止,我尝试使用IUserIdProvider,但这似乎不起作用。在前端,我设置了queryString如下: $.connection.hub.qs = "userId=" + $('#userText').val(); 以下是我的自定义IUserIdProvider:
public class CustomUserIdProvider : IUserIdProvider
{
    public string GetUserId(IRequest request)
    {
         return request.QueryString["userId"];
     }
 }

以下是我的 NotificationRepository 的样子。
public class NotificationRepository
{
    private readonly string _connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

    public IEnumerable<Notifications> GetUserNotifications(string userID)
    {
        var notifications = new List<Notifications>();

        using (var connection = new SqlConnection(_connString))
        {
            connection.Open();
            using (var command = new SqlCommand(String.Format(@"SELECT [ID], [UserID], [Message] FROM [dbo].[Notification] WHERE [UserID] = {0}", userID), connection))
            {
                command.Notification = null;

                var dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler((sender, e) => dependency_OnChange(sender, e, userID));

                if (connection.State == ConnectionState.Closed)
                {
                    connection.Open();
                }

                var reader = command.ExecuteReader();

                while (reader.Read())
                {
                    notifications.Add(item: new Notifications { ID = (int)reader["ID"], UserID = (int)reader["UserID"], Message = (string)reader["Message"] });
                }
            }
        }
        return notifications;
    }


    private void dependency_OnChange(object sender, SqlNotificationEventArgs e, string userID)
    {
        if (e.Type == SqlNotificationType.Change)
        {
            NotificationHub.SendNotifications(userID);
        }
    }
}

And this is my hub

public class NotificationHub : Hub
{
    private static string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();

    [HubMethodName("sendNotifications")]
    public static void SendNotifications(string userId)
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
        context.Clients.Client(userId).updateNotifications();
    }
}
1个回答

3

So I've figured out what the issue is in this scenario. When initialising the queryString

$.connection.hub.qs = "userId=" + $('#userText').val();

You must do this before you start the connection to the hub.


你能帮我解决这个问题吗?我无法向特定用户发送通知。 - naim shaikh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接