根据登录用户显示新消息计数

时间:2014-09-25 14:29:08

标签: c# asp.net signalr

目前正在开发一个用asp和c#开发的网站。使用信号器我每次在数据库中收到新消息时都设法发送新通知。但是,我现在遇到的问题是,如果 User1 有一条新消息而 User2 有2条新消息。它们都会显示给用户。因此 User1 会有一条新消息, User2 也会消息。我使用下面的代码

 [HubMethodName("Notifications")]
    public string SendNotifications()
    {
        string userName = HttpContext.Current.User.Identity.Name;

        using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString))
        {
            string query = "SELECT  NewMessageCount FROM Messages WHERE UserName=@UserName";

            using (SqlCommand command = new SqlCommand(query, connection))
            {
                SqlParameter para2 = new SqlParameter(@"UserName", userName);
                command.Parameters.Add(para2);
                command.Notification = null;
                DataTable dt = new DataTable();
                SqlDependency dependency = new SqlDependency(command);
                dependency.OnChange += new OnChangeEventHandler(dependency_OnChange);
                connection.Open();

                SqlDataReader reader = command.ExecuteReader();
                dt.Load(reader);
                if (dt.Rows.Count > 0)
                {
                    totalNewMessages = Int16.Parse(dt.Rows[0]["NewMessageCount"].ToString());
                }
            }
        }
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<NotificationHub>();
        return context.Clients.All.RecieveNotification(totalNewMessages);
    }

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

是的,因为您正在向所有人广播。您尚未指定特定连接。有关如何指定特定客户端/组的信息,请查看以下内容。 Selecting which clients will receive the RPC

答案 1 :(得分:0)

您应该使用Clients.User(userid)

context.Clients.User(userName).RecieveNotification(totalNewMessages);
相关问题