如何向用户发送SignalR消息?

时间:2018-10-02 11:28:29

标签: 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();

3 个答案:

答案 0 :(得分:1)

正在追寻相同的问题并从https://github.com/aspnet/SignalR/issues/2498获得解决方案

需要设置NameIdentifier声明。那是由SignalR检查的那个,而不是我假设的Name声明。我设置了NameIdentifier声明,并获得了非hub类,以将通知发送给特定用户。

答案 1 :(得分:0)

有一个客户端组件。您必须引用SignalR JS文件,创建一个连接,然后订阅来自服务器的特定消息。只有这样,发送该消息才能真正起作用。

<script src="~/lib/signalr/signalr.js"></script>
<script>
    const connection = new signalR.HubConnectionBuilder()
       .withUrl("/gameHub")
       .configureLogging(signalR.LogLevel.Information)
       .build();

    connection.on("Foo", (data) => {
        // do something
    });

    connection.start().catch(err => console.error(err.toString()));
</script>

然后,每当服务器发送"Foo"消息时,以上内容将使客户端运行上面为"Foo"定义的功能:

hubContext.Clients.User(User.Identity.Name).SendAsync("Foo", data);

答案 2 :(得分:0)

您正在将Users用作连接ID的存储。因此,对于每个用户名,您可以将消息发送到为该用户存储的每个客户端连接。像这样:

public void SendMessage(string username, object data)
{
    var connections = HubConnections.Users[Context.User.Identity.Name];

    foreach(var id in connections)
    {
        Clients.client(id).SendAsync("Foo", data);
    }
}