Home >Backend Development >C++ >How to Invoke SignalR Core Hub Methods from an ASP.NET Core Controller?
Invoking SignalR Core Hub Methods from Controller
In ASP.NET Core applications, it is sometimes necessary to invoke Hub methods from a controller. For instance, when external services perform tasks and need to notify connected clients through SignalR.
Solution 1 (Dynamic)
If you use the Microsoft.AspNetCore.SignalR library (version 1.0.0-alpha2-final), you can inject the IHubContext of your Hub into your controller. Here's an example:
[Route("API/vardesigncomm")] public class VarDesignCommController : Controller { [HttpPut("ProcessVarDesignCommResponse/{id}")] public async Task<IActionResult> ProcessVarDesignCommResponse(int id) { await this.HubContext.Clients.All.InvokeAsync("Completed", id); return new JsonResult(true); } private IHubContext<VarDesignHub> HubContext { get; set; } }
Solution 2 (Typed)
Consider creating an interface to define methods that the server can invoke on client hubs. This approach is known as "typed hub endpoints":
public interface ITypedHubClient { Task TaskCompleted(int id); } public class VarDesignHub : Hub<ITypedHubClient> { public Task TaskCompleted(int id) => Clients.All.InvokeAsync("Completed", id); }
In your controller, inject the typed HubContext and invoke methods:
[Route("API/demo")] public class DemoController : Controller { private IHubContext<VarDesignHub, ITypedHubClient> _chatHubContext; public DemoController(IHubContext<VarDesignHub, ITypedHubClient> chatHubContext) { _chatHubContext = chatHubContext; } [HttpGet] public IActionResult TaskCompleted(int id) { _chatHubContext.Clients.All.TaskCompleted(id); return Ok(); } }
The above is the detailed content of How to Invoke SignalR Core Hub Methods from an ASP.NET Core Controller?. For more information, please follow other related articles on the PHP Chinese website!