小编Aks*_*rma的帖子

如何使用 aspnetcore signalR 向特定用户发送消息?

我需要向特定用户发送通知。我正在使用 dotnet core 3.1。用于通知的 ASPNETCORE signalR。我可以将消息发送给所有客户端,但无法为特定用户发送消息。

编辑1

我的中心看起来像:

public class NotificationHub : Hub
{
    public override async Task OnConnectedAsync()
    {
        await Groups.AddToGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnConnectedAsync();
    }

    public override async Task OnDisconnectedAsync(Exception ex)
    {
        await Groups.RemoveFromGroupAsync(Context.ConnectionId, Context.User.Identity.Name);
        await base.OnDisconnectedAsync(ex);
    }
}
Run Code Online (Sandbox Code Playgroud)

我从控制器调用 SendAsync 方法如下:

 private IHubContext<NotificationHub> _hub;

    public NotificationController(IHubContext<NotificationHub> hub)
    {
        _hub = hub;
    }

[HttpGet]
    public IActionResult Get()
    {
        //_hub.Clients.All.SendAsync("SendMessage",
        _hub.Clients.All.SendAsync("SendMessage",
            new
            {
                val1 = getRandomString(),
                val2 = getRandomString(),
                val3 = getRandomString(),
                val4 = getRandomString()
            });

        return Ok(new { Message …
Run Code Online (Sandbox Code Playgroud)

c# signalr signalr-hub asp.net-core-signalr

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

asp.net-core-signalr ×1

c# ×1

signalr ×1

signalr-hub ×1