Call SignalR Core Hub Method from Controller
In ASP.NET Core applications, it is often necessary to communicate with SignalR hubs from controllers to update client-side applications with server-side events. Here are two approaches to achieve this:
Solution 1: Using Untyped HubContext
This method allows you to directly invoke methods on all connected clients. Inject the untyped IHubContext
public class VarDesignCommController : Controller { private readonly IHubContext<VarDesignHub> _hubContext; public VarDesignCommController(IHubContext<VarDesignHub> hubContext) { _hubContext = hubContext; } [HttpPut("ProcessVarDesignCommResponse/{id}")] public async Task<IActionResult> ProcessVarDesignCommResponse(int id) { await _hubContext.Clients.All.InvokeAsync("TaskCompleted", id); return new JsonResult(true); } }
Solution 2: Using Typed Hubs and Interfaces
This approach uses typed hubs and interfaces to define client-side methods that can be called from the controller.
Create an interface for the hub client:
public interface ITypedHubClient { Task TaskCompleted(int id); }
Inherit from Hub
public class VarDesignHub : Hub<ITypedHubClient> { public async Task TaskCompleted(int id) { await Clients.All.InvokeAsync("Completed", id); } }
Inject the typed hub context into the controller:
public class VarDesignCommController : Controller { private readonly IHubContext<VarDesignHub, ITypedHubClient> _hubContext; public VarDesignCommController(IHubContext<VarDesignHub, ITypedHubClient> hubContext) { _hubContext = hubContext; } [HttpPut("ProcessVarDesignCommResponse/{id}")] public async Task<IActionResult> ProcessVarDesignCommResponse(int id) { await _hubContext.Clients.All.TaskCompleted(id); return new JsonResult(true); } }
The above is the detailed content of How Can I Call a SignalR Core Hub Method from an ASP.NET Core Controller?. For more information, please follow other related articles on the PHP Chinese website!