asp.net-core - 如何向用户发送 SignalR 消息?
问题描述
客户端如何授权向用户发送消息?
从控制器发送
hubContext.Clients.User(User.Identity.Name).SendAsync();
目前消息未发送。我需要在 OnConnection() 中添加一些东西吗?或者 SignalR 有没有现成的 ConnectionId 和 User.Identity.Name 的映射机制?
这就是我目前实现它的方式,但在我看来并不完全正确。问题是如何制作相同的标准工具?
public static class HubConnections
{
public static Dictionary<string, List<string>> Users = new Dictionary<string, List<string>>();
public static List<string> GetUserId(string name)
{
return Users[name];
}
}
public class GameHub : Hub
{
public override Task OnConnectedAsync()
{
if (Context.User.Identity.IsAuthenticated
&& HubConnections.Users.ContainsKey(Context.User.Identity.Name)
&& !HubConnections.Users[Context.User.Identity.Name].Contains(Context.ConnectionId))
HubConnections.Users[Context.User.Identity.Name].Add(Context.ConnectionId);
else
HubConnections.Users.Add(Context.User.Identity.Name, new List<string> { Context.ConnectionId });
return base.OnConnectedAsync();
}
public override Task OnDisconnectedAsync(Exception exception)
{
if (Context.User.Identity.IsAuthenticated) HubConnections.Users.Remove(Context.User.Identity.Name);
return base.OnDisconnectedAsync(exception);
}
}
正如我上面所说,我只是这样尝试,但它不起作用
hubContext.Clients.User(User.Identity.Name).SendAsync();
解决方案
正在追逐同样的问题并从https://github.com/aspnet/SignalR/issues/2498获得解决方案
需要设置 NameIdentifier 声明。那是 SignalR 检查的,而不是我假设的 Name 声明。我设置了 NameIdentifier 声明,并让我的非集线器类向特定用户发送通知。
推荐阅读
- angular - 如何更改响应式表单中日期的格式?
- .htaccess - 防止 htaccess 表单重定向到 url 中的目录
- javascript - 在控制台中记录 flash 消息会导致失败(connect-flash)
- database - 批处理、在线处理还是两者兼而有之?
- postgresql - 如何提高 postgres / pgbouncer 的性能
- ios - iOS WebRTC网状视频电话会议内存增加问题
- r - gglot2::geom_abline 在对数图中使用默认设置失败(ggplot2 v3.3.4)
- python-3.x - 延迟主线程执行,直到其他线程上不存在锁:最佳实践?
- css - I want to display footer Template Page Number to Right of Page
- python - Python - 如何在另一个函数中使用函数