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

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

我需要向特定用户发送通知。我正在使用 dotnet 核心 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);
    }
}

我从 Controller 调用 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 = "Request Completed" });
    }

最佳答案

您可以通过 user id 向特定用户发送消息

在此示例中,我们将尝试获取当前用户信息并使用用户 ID 将一些数据发送回该用户:

在枢纽中:

public async Task GetInfo()
{
    var user = await _userManager.GetUserAsync(Context.User);

    await Clients.User(user.Id).SendCoreAsync("msg", new object[] { user.Id, user.Email });
}

在客户端:

connection.on('msg', function (...data) {
    console.log('data:', data); // ["27010e2f-a47f-4c4e-93af-b55fd95f48a5", "foo@bar.com"]
});

connection.start().then(function () {
    connection.invoke('getinfo');
});

注:确保您已经在 UseEndpoints 中映射了集线器方法:

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller=Home}/{action=Index}/{id?}");

    endpoints.MapHub<YourHubName>("/yourhubname");
});

关于c# - 如何使用aspnetcore signalR向特定用户发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60275474/

相关文章:

c# - 添加多个成员 - Redis Booksleeve 不支持分数值

c# - C#中For循环的一个简单问题

c# - 空上下文.用户

signalr - 使用 Signalr/PersistentConnection 将服务器消息发送到连接的客户端

c# - Asp.net Core 不收集垃圾

asp.net - 从 SignalR Hub 调用方法时出现问题。调用失败。 promise 被拒绝

angularjs - SignalR 2-多个集线器实例时,客户端不会收到从服务器发送的所有消息

asp.net-mvc - 看不到来 self 的 SignalR 集线器的跟踪输出

asp.net - SignalR 导致服务器上出现错误请求 400

c# - 如何使用 DataContractJsonSerializer 将类类型而不是命名空间序列化为 Json 字符串