首页 > 解决方案 > signalR - 向特定用户发送消息

问题描述

我正在阅读此处SignalR的Microsoft 教程。

一切正常,但是,我想尝试更改代码ChatHub#SendMessage以向特定用户发送消息。

所以我修改了这样的代码:

public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        //await Clients.All.SendAsync("ReceiveMessage", user, message);

        await Clients.User(user).SendAsync("ReceiveMessage", message);
    }
}

但是,用户永远不会收到消息。仅当您使用时才会发送消息Clients.All.SendAsync(即上面注释掉的行)。

我还做了更多的研究,从这个答案中发现,也许我需要实现一个自定义用户提供程序。所以我实现了一个:

public class CustomUserIdProvider : IUserIdProvider
{
    public string GetUserId(HubConnectionContext connection)
    {
        return "user1";
    }
}

然后在 中Startup.cs,我注册了这个提供者:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();
    services.AddSingleton<IUserIdProvider, CustomUserIdProvider>();
    services.AddSignalR();
}

然后我尝试Context.UserIdentifier在发送消息时使用,如下所示:

public async Task SendMessage(string user, string message)
{
    //await Clients.All.SendAsync("ReceiveMessage", user, message);

    await Clients.User(Context.UserIdentifier).SendAsync("ReceiveMessage", message);
}

但它似乎仍然没有发送消息。

我究竟做错了什么?

标签: asp.net-coresignalr

解决方案


我这样做的方式是,当用户登录时,我将它们添加到 SignalR 组,该组是用户的 ID 或名称。这样一来,对于该一个用户来说,它就是一个独特的组。然后我将消息发送到该组。只有该用户会收到该消息,因为他们是该组中唯一的用户。

客户端代码:

// Optional: authenticate with a server, get a token... or send username/password in following request

_hub = new HubConnectionBuilder()
    .WithUrl(_envSettings.CreatePlayerServiceHubPath(), x =>
    {
        x.Headers.Add("x-lcc-version", AppEnvironment.Application.Version);
        x.Headers.Add("x-lcc-username", username);
        x.Headers.Add("x-lcc-authorization", token);
    })
    .AddNewtonsoftJsonProtocol()
    .Build();

_hub.Closed += OnSignalRDisconnectedFromServerAsync;
SetupRPCs();
await _hub.StartAsync().ConfigureAwait(false);

服务器端代码:

public override async Task OnConnectedAsync()
{
    var userName = Context.GetHttpContext().Request.Headers["x-lcc-username"];
    var token = Context.GetHttpContext().Request.Headers["x-lcc-authorization"];
    
    // Optional: validate authorization
    
    await Groups.AddToGroupAsync(Context.ConnectionId, userName);
    
    // Then when you want to send a message to the user:
    await Clients.Group(userName).SendAsync("hello", "world");
}

很好的是,当用户断开连接时,它会Group自动消失。您不必维护您正在创建的那些组。

我知道这可能不是您正在寻找的 100%,但它是如何处理与其他场景类似的情况的一个想法。


推荐阅读