SignalR is a library that brought push notifications to ASP .NET web applications. It abstracted away the complexity of dealing with websockets and other front-end technologies necessary for a web application to spontaneously push out updates to client applications, and provided an easy programming model.
Essentially, SignalR allows us to implement publish/subscribe on the server. Clients, which are typically (but not necessarily) webpages, subscribe to a hub, which can then push updates to them. These updates can be sent spontaneously by the server (e.g. stock ticker) or triggered by a message from a client (e.g. chat).
The old SignalR, however, is not compatible with ASP .NET Core. So if you wanted to have push notifications in your web application, you had to look elsewhere… until recently. Microsoft shipped their first alpha release of SignalR Core (SignalR for ASP .NET Core 2.0) a few weeks ago, and the second alpha was released just yesterday. They also have some really nice samples we can learn from.
This article explains how to quickly get started with SignalR Core, by means of a simple Hello World application that combines a simple server-side hub with a trivial JavaScript client. It is essentially the first example from my “Getting Started with SignalR“, ported to SignalR Core.
The source code for this article is in the SignalRCoreHello folder at the Gigi Labs BitBucket Repository.
Hello SignalR Core: Server Side
This example is based on SignalR Core alpha 2, and uses ASP .NET Core 2 targeting .NET Core 2. As this is pre-release software, APIs may change.
Let’s start off by creating a new ASP .NET Core Web Application in Visual Studio 2017. We can start off simple by using the Empty project template:
This project template should come with a reference to the Microsoft.AspNet.All NuGet package, giving you most of what you need to create our web application.
In addition to that, we’ll need to install the NuGet package for SignalR. Note that we need the -Pre
switch for now because it is still prerelease.
Install-Package Microsoft.AspNetCore.SignalR -Pre
Next, let’s add a Hub. Just add a new class:
public class HelloHub : Hub { public Task BroadcastHello() { return Clients.All.InvokeAsync("hello"); } }
In SignalR Core, a class that inherits from Hub is able to communicate with any clients that are subscribed to it. This can be done in several ways: broadcast to all clients or all except one; send to a single client; or send to a specific group. In this case, we’re simply broadcasting a “hello” message to all clients.
In the Startup class, we need to remove the default “Hello world” code and register our Hub instead. It should look something like this:
public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddSignalR(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseFileServer(); app.UseSignalR(routes => { routes.MapHub<HelloHub>("hello"); }); } }
UseSignalR()
is where we register the route by which our Hub will be accessed from the client side. UseFileServer()
is there just to serve the upcoming HTML and JavaScript.
Hello SignalR Core: Client Side
In order to have a webpage that talks to our Hub, we first need a couple of scripts. We’ll get these using npm, which you can obtain by installing Node.js if you don’t have it already.
npm install @aspnet/signalr-client npm install jquery
The first package is the client JavaScript for SignalR Core. At the time of writing this article, the file you need is called signalr-client-1.0.0-alpha2-final.js. The second package is jQuery, which is no longer required by SignalR Core, but will make life easier for our front-end code. Copy both signalr-client-1.0.0-alpha2-final.js and jquery.js into the wwwroot folder.
Next, add an index.html file in the wwwroot folder. Add references to the aforementioned scripts, a placeholder for messages (with ID “log” in this example), and a little script to wire things up:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello SignalR Core!</title> <script src="jquery.js"></script> <script src="signalr-client-1.0.0-alpha2-final.js"></script> <script type="text/javascript"> $(document).ready(function () { var connection = new signalR.HubConnection('/hello'); connection.on('hello', data => { $("#log").append("Hello <br />"); }); connection.start() .then(() => connection.invoke('BroadcastHello')); }); </script> </head> <body> <div id="log"></div> </body> </html>
This JavaScript establishes a connection to the hub, registers a callback for when a “hello” message is received, and calls the BroadcastHello()
method on the hub:
The way we implemented our Hub earlier, it will send a “hello” message to all connected clients.
Let’s give that a try now:
Good! The connection is established, and we’re getting something back from the server (i.e. the Hub). Let’s open a couple more browser windows at the same endpoint:
Here, we can see that each time a new window was opened, a new “hello” message was broadcasted to all connected clients. Since we are not holding any state, messages are sent incrementally, so newer clients that missed earlier messages will be showing fewer messages.
The Chat Sample
If you want to see a more elaborate example, check out the Chat sample from the official SignalR Core samples:
The principle is the same, but the Chat sample is a little more interesting.
Good post.
I am trying to use Azure Redis Cache for SignalR backplane and couldn’t find anything which tells you how to provide connection string. All the posts I’ve seen just mention use
services.AddSignalR().AddRedis();
But don’t tell you where to setup azure Redis connection string. Have you used Redis for backplane or have any idea how to set it up?
Thanks
I haven’t gone that far myself yet, and there doesn’t seem to be much in the way of documentation. Let me know if you figure this out though!