Practical ASP.NET Core SignalR: Basics

Practical ASP.NET Core SignalRIn 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.

  1. Course Overview
  2. ASP.NET Core SignalR Overview

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 the IServiceCollection 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.

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

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.js

JavaScript

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:

  1. Check out my Practical ASP.NET Core SignalR playlist on my CodeOpinion YouTube channel.
  2. Access the full course now by enrolling for free on Teachable.
  3. Follow along with the blog post series here on CodeOpinion.com
    1. Course Overview
    2. ASP.NET Core SignalR Overview
    3. Basics
    4. Server Hubs
    5. HubContext
    6. Authorization
    7. Scaling with Redis
    8. Scaling with Azure SignalR Service

Source Code

All of the source code for this blog post and this course is available the Practical.AspNetCore.SignalR repo on GitHub.