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

The*_*Saw 12 c# asp.net-core asp.net-core-signalr

我已经使用新发布的ASP.NET Core 2.1成功设置了SignalR服务器和客户端.我通过ChatHub扩展建立了一个聊天室Hub:每当有来自客户端的消息时,服务器就会通过它将其反弹回来Clients.Others.

我还不了解的是如何向客户端发送消息而不是作为对传入消息的响应.如果服务器正在工作并产生结果,我如何获得访问权限Hub以便向特定客户端发送消息?(或者我甚至需要访问Hub?是否有其他方式发送消息?)

搜索此问题很困难,因为大多数结果来自旧版本的ASP.NET和SignalR.

Sim*_*Ged 8

您可以将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.InvokeAsync("ReceiveMessage", message);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,您可以将注入NotifyService到您的类中并向所有客户端发送消息:

public class SomeClass
{
    private readonly NotifyService _service;

    public SomeClass(NotifyService service)
    {
        _service = service;
    }

    public Task Send(string message)
    {
        return _service.SendNotificationAsync(message);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 一些变化:`InvokeAsync` 现在是 `SendAsync` (https://github.com/aspnet/SignalR/issues/1300) 并确保添加命名空间 `using Microsoft.AspNetCore.SignalR;` 以获得扩展需要的方法。另见 https://github.com/aspnet/SignalR/issues/2239 (2认同)