C# 信号器核心接收来自特定用户的消息
SignalR core是非常新的,因此详细介绍如何使用它的文档非常少。 我已经完成了Microsoft的教程,并成功地向所有客户端发送了消息。现在我想为特定用户发送C# 信号器核心接收来自特定用户的消息,c#,.net-core,signalr,C#,.net Core,Signalr,SignalR core是非常新的,因此详细介绍如何使用它的文档非常少。 我已经完成了Microsoft的教程,并成功地向所有客户端发送了消息。现在我想为特定用户发送 public Task SendPrivateMessage(string user, string message, string to) { return Clients.User(to).SendAsync("ReceiveMessage", user, message); } “to”值是我从 public ov
public Task SendPrivateMessage(string user, string message, string to)
{
return Clients.User(to).SendAsync("ReceiveMessage", user, message);
}
“to”值是我从
public override Task OnConnectedAsync()
{
Console.WriteLine("New ID Connected: " + Context.ConnectionId);
return base.OnConnectedAsync();
}
这是我的客户:
public async void InitSignalRAsync()
{
ChatMessage mess = new ChatMessage();
hubConnection = new HubConnectionBuilder().WithUrl("http://localhost:5000/chatHub").Build();
await hubConnection.StartAsync();
hubConnection.On<string, string>("ReceiveMessage", async (user, message) =>
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
mess.user = user;
mess.message = message;
Messages.Add(mess);
});
});
}
private void Send_Click(object sender, RoutedEventArgs e)
{
hubConnection.InvokeAsync("SendPrivateMessage", User.Text, Text.Text, To.Text);
}
public异步void initSignalAsync()
{
ChatMessage mess=新建ChatMessage();
hubConnection=新的HubConnectionBuilder()。带有URL(“http://localhost:5000/chatHubBuild();
等待hubConnection.StartAsync();
hubConnection.On(“接收消息”,异步(用户,消息)=>
{
wait Dispatcher.RunAsync(CoreDispatcherPriority.Normal,()=>
{
mess.user=用户;
mess.message=消息;
消息。添加(混乱);
});
});
}
私有无效发送\单击(对象发送方,路由目标)
{
hubConnection.InvokeAsync(“SendPrivateMessage”,User.Text,Text.Text,To.Text);
}
控制台没有记录任何错误,所以我猜它确实发送了,但为什么我不能接收它?对于通过客户端的连接ID发送到客户端,您应该使用Clients.client(coonnectionID) ,Clients.User()用于按用户Id发送给uniqe用户。要按用户Id发送消息,您可以尝试以下操作: -创建CustomUserIdProvider:
public class CustomUserIdProvider: IUserIdProvider
{
public virtual string GetUserId(HubConnectionContext connection)
{
//get current user id by httpcontext
}
}
然后在startup.cs中:
services.AddSignalR();
services.AddSignalRCore();
services.AddSingleton<IUserIdProvider, CustomUserIdProvider>();
有关更多信息,请转到此如何获取当前用户ID?Context.User.Identity.Name
public void Send(string userId, string message)
{
Clients.User(userId).send(message);
}