Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I've successfully setup a SignalR server and client using the newly released ASP.NET Core 2.1. I built a chat room by making my ChatHub extend Hub: whenever a message comes in from a client, the server blasts it back out via Clients.Others.

What I do not yet understand is how to send a message to clients not as a response to an incoming message. If the server is doing work and produces a result, how do I gain access to the Hub in order to message particular clients? (Or do I even need access to the Hub? Is there another way to send messages?)

Searching this issue is difficult as most results come from old versions of ASP.NET and SignalR.

like image 640
TheBuzzSaw Avatar asked Jun 10 '18 21:06

TheBuzzSaw


People also ask

How do I send a message to a group in SignalR?

When user click on send button, the message to be posted to server side using signalR connection hub. Thus whenever you post any message after clicking the join group button, the message will appear to all the clients who has joined the group.


2 Answers

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.SendAsync("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);     } } 
like image 81
Simply Ged Avatar answered Sep 22 '22 14:09

Simply Ged


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

Details you will find there:

Call SignalR Core Hub method from Controller

like image 39
Stephu Avatar answered Sep 24 '22 14:09

Stephu