In ASP.NET Core SignalR, how do I send a message from the server to a client?

主宰稳场 提交于 2019-12-05 00:22:39
Simply Ged

You can inject the IHubContext<T> class into a service and call the clients using that.

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);
    }
}

Now you can inject the NotifyService into your class and send messages to all clients:

public class SomeClass
{
    private readonly NotifyService _service;

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

    public Task Send(string message)
    {
        return _service.SendNotificationAsync(message);
    }
}

Simple inject the hubcontext into the class where you use the hubcontext.

Details you will find there:

Call SignalR Core Hub method from Controller

There are now official Microsoft Docs for the SignalR HubContext that answer your question https://docs.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-2.1

But yes, as others have pointed out, you need to get an instance of IHubContext via dependency injection to access hub methods outside of the hub.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!