asp.net-core - 如何向用户发送 SignalR 消息?

标签 asp.net-core signalr

客户端如何授权向用户发送消息?

从 Controller 发送

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 声明,并让我的非中心类向特定用户发送通知。

关于asp.net-core - 如何向用户发送 SignalR 消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52607458/

相关文章:

c# - 如何在 ASP.NET Core MVC 中请求并显示实时 Web api 数据?

c# - SignalR 无法读取未定义的属性客户端

c# - SignalR - Websockets - 超出缓冲区长度

c# - SignalR:使用 moq 框架模拟 IHub 并测试他的方法

c# - 使用 Twilio .netcore Blazor 服务器端发送短信通知

c# - Asp.Net Core 重定向到 Action 但不允许直接调用 Action ?

c# - 容器如何实际解析 ILogger<T>

c# - SignalR 客户端中心代理未定义

c# - 如何从 .NET Core 3.1 中的 DI 获取 SignalR IHubContext?

linux - Linux 上的 ASP.NET Core Windows 身份验证