Server HubsA hub is a primary point at which all communication between client and server occur. You define methods in a hub that can be called by the client. And in the client code, we can define methods that our hub can call. First thing is first, we need to install the SignalR package from NuGet. The simplest way is to modify your csproj by adding:
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0" />
Message HubI’m going to create the simplest hub which will just send a message to all connected clients.
Startup.csNext, we need to add SignalR to the
IServiceCollection in the
ConfigureServices method. As well, we configure a route to our message hub in the
From here you will want to copy the client file from node_modules/signalr/dist/browser/signalr.js to your wwwroot/lib/signalr.jsnpm install @aspnet/signalr
Razor PageNext, I’m going to create a Razor page that will just contain a simple textarea and button that we will wire up to the SignalR hub. It will also contain a script tag to reference the signalr.js file and a file we will create next called messages.js
Get The Course!You’ve got several options:
- Check out my Practical ASP.NET Core SignalR playlist on my CodeOpinion YouTube channel.
- Access the full course now by enrolling for free on Teachable.
- Follow along with the blog post series here on CodeOpinion.com