Search code examples
.net-coresignalrsignalr-hub

Can an API in .NET Core 3.1 be made a client of a SignalR hub?


I am developing an application in Xamarin which connects to both a .Net Core 3.1 API and a SignalR server with its corresponding hub. Right now I launch the request to send a notification from the Xamarin application itself, but I would like this request to be sent from the API instead of from the app, and with the existing documentation I have not been able to find a solution.


Solution

  • You can send various notifications to the clients after injecting HubContext in your API. You can inject it for example in your controller class :

    public class MyController()
    {
        private readonly IHubContext<MyHub> hub;
    
        public MyController(IHubContext<MyHub> hub)
        {
            this.hub = hub;
        }
    
        public Task MyMethodAsync(string message)
        {
            return hub.Clients.All.SendAsync("MessageName", message);
        }
    
    }