繁体   English   中英

在 ASP.NET Core SignalR 中,如何从服务器向客户端发送消息?

[英]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);
    }
}

简单地将 hubcontext 注入到使用 hubcontext 的类中。

您会在那里找到详细信息:

从控制器调用 SignalR Core Hub 方法

现在有 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM