SignalR Core provides a powerful real-time communication mechanism for ASP.NET Core applications. This article addresses the common scenario of calling a SignalR hub method from a controller.
The provided example demonstrates the need to notify connected clients upon the completion of an external operation initiated from a Windows service. Since the service cannot directly interact with SignalR, we explore two potential solutions.
Inject the IHubContext for the desired hub into the controller:
public class VarDesignCommController : Controller { public VarDesignCommController(IHubContext<VarDesignHub> hubcontext) { HubContext = hubcontext; } ... }
Then invoke the hub method:
await this.HubContext.Clients.All.InvokeAsync("Completed", id);
For more granular control, create a typed client interface:
public interface ITypedHubClient { Task BroadcastMessage(string name, string message); }
Inherit from the Hub class and define the client-side method:
public class ChatHub : Hub<ITypedHubClient> { public void Send(string name, string message) { Clients.All.BroadcastMessage(name, message); } }
Inject the typed hub context and invoke the method:
// In VarDesignCommController [Route("api/demo")] public class DemoController : Controller { IHubContext<ChatHub, ITypedHubClient> _chatHubContext; public DemoController(IHubContext<ChatHub, ITypedHubClient> chatHubContext) { _chatHubContext = chatHubContext; } [HttpGet] public IEnumerable<string> Get() { _chatHubContext.Clients.All.BroadcastMessage("test", "test"); return new string[] { "value1", "value2" }; } }
The above is the detailed content of How to Call a SignalR Hub Method from an ASP.NET Core Controller?. For more information, please follow other related articles on the PHP Chinese website!