更新于
注意:我在一个电子商务网站上工作,即使用户处于离线状态,用户也需要能够接收消息(消息将存储在数据库中,一旦在线,他们就可以阅读)。
执行以下操作以安全方式使用随机生成的 connectionId 发送消息:
首先添加以下类来跟踪用户的connectionIds来了解用户是在线还是离线
public static class ChatHubUserHandler
{
public static ConcurrentDictionary<string, ChatHubConnectionViewModel> ConnectedIds =
new ConcurrentDictionary<string, ChatHubConnectionViewModel>(StringComparer.InvariantCultureIgnoreCase);
}
public class ChatHubConnectionViewModel
{
public string UserName { get; set; }
public HashSet<string> UserConnectionIds { get; set; }
}
配置ChatHub
如下
使类上的ChatHub
安全添加[Authorize]
属性ChatHub
。
[Authorize]
public class ChatHub : Hub
{
private string UserName => Context.User.Identity.Name;
private string ConnectionId => Context.ConnectionId;
// Whenever a user will be online randomly generated connectionId for
// him be stored here.Here I am storing this in Memory, if you want you
// can store it on database too.
public override Task OnConnected()
{
var user = ChatHubUserHandler.ConnectedIds.GetOrAdd(UserName, _ => new ChatHubConnectionViewModel
{
UserName = UserName,
UserConnectionIds = new HashSet<string>()
});
lock (user.UserConnectionIds)
{
user.UserConnectionIds.Add(ConnectionId);
}
return base.OnConnected();
}
// Whenever a user will be offline his connectionId id will be
// removed from the collection of loggedIn users.
public override Task OnDisconnected(bool stopCalled)
{
ChatHubConnectionViewModel user;
ChatHubUserHandler.ConnectedIds.TryGetValue(UserName, out user);
if (user != null)
{
lock (user.UserConnectionIds)
{
user.UserConnectionIds.RemoveWhere(cid => cid.Equals(ConnectionId));
if (!user.UserConnectionIds.Any())
{
ChatHubUserHandler.ConnectedIds.TryRemove(UserName, out user);
}
}
}
return base.OnDisconnected(stopCalled);
}
}
现在使用以下模型类将消息存储到数据库。您还可以根据您的确切需要自定义消息类别。
public class Message
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long MessageId { get; set; }
[ForeignKey("Sender")]
public string SenderId { get; set; }
[ForeignKey("Receiver")]
public string ReceiverId { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string MessageBody { get; set; }
public DateTime MessageSentAt { get; set; }
public bool IsRead { get; set; }
public User Sender { get; set; }
public User Receiver { get; set; }
}
然后在消息控制器中:
这只是一个示例代码。您可以根据您的确切需要自定义代码。
[HttpPost]
public async Task<ActionResult> SendMessage(string messageBody, string receiverAspNetUserId)
{
string loggedInUserId = User.Identity.GetUserId();
Message message = new Message()
{
SenderId = loggedInUserId,
ReceiverId = receiverAspNetUserId,
MessageBody = messageBody,
MessageSentAt = DateTime.UtcNow
};
_dbContext.Messages.Add(message);
_dbContext.SaveChangesAsync();
// Check here if the receiver is currently logged in. If logged in,
// send push notification. Send your desired content as parameter
// to sendPushNotification method.
if(ChatHubUserHandler.ConnectedUsers.TryGetValue(receiverAspNetUserId, out ChatHubConnectionViewModel connectedUser))
{
List<string> userConnectionIds = connectedUser.UserConnectionIds.ToList();
if (userConnectionIds.Count > 0)
{
var chatHubContext = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
chatHubContext.Clients.Clients(userConnectionIds).sendPushNotification();
}
}
return Json(true);
}
现在的问题是,如果在接收方离线时发送消息怎么办?
好的!在这种情况下,您可以通过两种方式处理推送通知!接收者在线后立即调用 ajax 方法或 SignalR Hub 方法来绑定通知。另一种方法是在布局页面中使用部分视图作为通知区域。我个人更喜欢对通知区域使用局部视图。
希望对你有帮助!