This blog post is apart of a course that is a complete step-by-setup guide on how to build real-time web applications using ASP.NET Core SignalR. By the end of this course, you’ll be able to build real-world, scalable, production applications using the tools and techniques provided in this course.
If you haven’t already, check out the prior sections of this course.
A 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" />
I’m going to create the simplest hub which will just send a message to all connected clients.
Next, we need to add SignalR to the
IServiceCollection in the
ConfigureServices method. As well, we configure a route to our message hub in the
npm install @aspnet/signalr
From here you will want to copy the client file from node_modules/signalr/dist/browser/signalr.js to your wwwroot/lib/signalr.js
Next, 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
Now they are referencing messages.js, let’s actually create it. This file will provide the functionality to connect to our SignalR Server Hub, send messages to the hub, and receive messages from the hub.
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
All of the source code for this blog post and this course is available the Practical.AspNetCore.SignalR repo on GitHub.