Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
In this section, I’m going to create a simple ASP.NET Core application that will contain a SignalR Hub, Razor Page, and a JavaScript Client. 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.Server Hubs
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" />
Message Hub
I’m going to create the simplest hub which will just send a message to all connected clients.Startup.cs
Next, we need to add SignalR to theIServiceCollection
in the ConfigureServices
method. As well, we configure a route to our message hub in the Configure
Method.
SignalR JavaScript Client
First thing will be to get the JavaScript client library from npm.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 Page
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.jsJavaScript
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