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

Aks*_*rma 7 c# signalr signalr-hub asp.net-core-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 = "Request Completed" });
    }
Run Code Online (Sandbox Code Playgroud)

Tân*_*Tân 3

您可以通过用户 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 });
}
Run Code Online (Sandbox Code Playgroud)

在客户端中:

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

connection.start().then(function () {
    connection.invoke('getinfo');
});
Run Code Online (Sandbox Code Playgroud)

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

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

    endpoints.MapHub<YourHubName>("/yourhubname");
});
Run Code Online (Sandbox Code Playgroud)