9/26/2019 Admin

Connecting Blazor to Azure SignalR Service


image

You can properly scale your Blazor application by connecting it to an Azure SignalR Service.

Create SignalR Service

image

We will need a Azure SignalR Service.

If you do not already have a Azure SignalR Service, log into the Azure Portal, and select Create a resource and search for SignalR Service.

image

Click Create.

image

You can initially choose the Free tier.

image

After the service is created, select Keys, and copy the Connection String (you will need it in the later steps).

image

Under Settings, set Service Mode to either Default or Classic.

Create the Blazor Application

image

Open Visual Studio 2019.

image

Create a new Blazor (server-side) project.

image

Hit F5 and run the project

image

The app will display

Stop debugging.

Add SignalR Service

image

Right-click on the Solution node and select Manage NuGet Packages...

image

Search for and install Microsoft.Azure.SignalR



image

Open the Startup.cs file in the Server project.

image

Change the ConfigureServices method to the following:

								services.AddSignalR().AddAzureSignalR(                 "{{ Your Azure SignalR Services Connection String }}");
							





Note: Replace {{ Your Azure SignalR Servces Connection String }} with the connection string you copied earlier.

image

When we run the application and use it, we can look in Azure and see the traffic.

Using User Secrets

image

It is recommended that you don’t store the connection string in the code.

For example, if you check this code into GitHub that would be really bad…

image

In Visual Studio, right-click on the project and select Manage User Secrets.

image

This will open a file called secrets.json in a location on your local computer.

image

Add a line:

"Azure:SignalR:ConnectionString": "{{ Your Azure SignalR Servces Connection String }}"
							



Note: Replace {{ Your Azure SignalR Servces Connection String }} with the connection string you copied earlier.

Save and close the file.

image

If you now edit the Project File

image

You will now see an entry pointing to the user secrets file.

image

Open the Startup.cs file.

Add the following using statement:

using Microsoft.Extensions.Configuration;
							

Add the following code to the Startup class:

								public IConfiguration Configuration { get; }         public Startup(IConfiguration configuration)         {             Configuration = configuration;         }
							

In the ConfigureServices method, change the services.AddSignalR().AddAzureSignalR line to:

services.AddSignalR().AddAzureSignalR(Configuration["Azure:SignalR:ConnectionString"]);
							

Links

Blazor.net

Server-side Blazor with Azure SignalR Service

What’s new in Azure SignalR 1.1.0 Preview 1

Safe storage of app secrets in development in ASP.NET Core

An error has occurred. This application may no longer respond until reloaded. Reload 🗙