SignalR向特定客户端发送消息

时间:2016-05-22 17:28:19

标签: c# asp.net signalr signalr-hub

我有一个带有静态方法的集线器,该方法当前向所有用户广播通知。

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是userID并将其发送到服务器类,例如

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映射到输入的用户ID?

我已经阅读了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);
        }
    }
}
  

这是我的中心

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 个答案:

答案 0 :(得分:3)

  

所以我已经弄清楚了这个场景中的问题。什么时候   初始化queryString

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

在开始与集线器的连接之前,必须执行此操作。