我需要向特定用户发送通知。我正在使用 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/