【发布时间】:2021-09-13 19:19:01
【问题描述】:
客户端如何授权向用户发送消息?
从控制器发送
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();
【问题讨论】:
-
请查看文档,它的解释和记录都很好:docs.microsoft.com/en-us/aspnet/core/tutorials/…
-
重读不止一次。我没有找到必要的信息
-
问题非常广泛,我们需要更多代码,请展示您尝试过的内容,可能有问题的类更详细。
-
已更新,请查看
标签: asp.net-core signalr