[英]In ASP.NET Core SignalR, how do I send a message from the server to a client?
我已经使用新发布的 ASP.NET Core 2.1 成功设置了 SignalR 服务器和客户端。 我通过让我的ChatHub
扩展Hub
构建一个聊天室:每当来自客户端的消息ChatHub
时,服务器都会通过Clients.Others
其发送Clients.Others
。
我还不明白的是如何向客户端发送消息而不是作为对传入消息的响应。 如果服务器正在工作并产生结果,我如何访问Hub
以向特定客户端发送消息? (或者我什至需要访问Hub
?还有其他发送消息的方式吗?)
搜索此问题很困难,因为大多数结果来自旧版本的 ASP.NET 和 SignalR。
您可以将IHubContext<T>
类注入服务并使用它调用客户端。
public class NotifyService
{
private readonly IHubContext<ChatHub> _hub;
public NotifyService(IHubContext<ChatHub> hub)
{
_hub = hub;
}
public Task SendNotificationAsync(string message)
{
return _hub.Clients.All.SendAsync("ReceiveMessage", message);
}
}
现在您可以将NotifyService
注入您的类并向所有客户端发送消息:
public class SomeClass
{
private readonly NotifyService _service;
public SomeClass(NotifyService service)
{
_service = service;
}
public Task Send(string message)
{
return _service.SendNotificationAsync(message);
}
}
现在有 SignalR HubContext 的官方 Microsoft Docs 可以回答您的问题https://docs.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-2.1
但是是的,正如其他人指出的那样,您需要通过依赖注入获取 IHubContext 的实例才能访问集线器之外的集线器方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.