Setting up SignalR Hub
Learn to add a hub in a SignalR project.
Overview
The server-side SignalR components center around the so-called Hub. SignalR Hub is equivalent to MVC or Web API controller. It is identical to gRPC (Remote Procedure Calls) service implementation. It’s a class with a collection of methods that SignalR clients will be able to trigger remotely.
We’ll add a basic example of a Hub to our project and register all necessary dependencies. Then, we’ll go through its structure in a little more detail.
Adding SignalR Hub to the project
We’ll follow similar conventions to MVC. As we have Models
, Views
, and Controllers
folders inside the SignalRServer
project, we will add another folder and call it Hubs
, then we’ll create a LearningHub.cs
file inside this folder.
-LearningSignalR-DotnetClient-DotnetClient.csproj-Program.cs
Next, we'll populate the LearningHub.cs
file with the following content:
using Microsoft.AspNetCore.SignalR;namespace SignalRServer.Hubs{public class LearningHub : Hub{public async Task BroadcastMessage(string message){await Clients.All.SendAsync("ReceiveMessage", message);}public override async Task OnConnectedAsync(){await base.OnConnectedAsync();}public override async Task OnDisconnectedAsync(Exception? exception){await base.OnDisconnectedAsync(exception);}}}
Note: You can use the terminal below for this task and use the
nano
command for file editing.
SignalR Hub overview
So, let’s go through the structure of the class. This is a basic example, so don’t worry, we won’t be overwhelmed with the information.
Add the Hub
class
First, a class that we want to use as a SignalR Hub needs to inherit from the ...