Use ASP.NET Core SignalR with Blazor WebAssembly

By Daniel Roth and Luke Latham

Important

Blazor WebAssembly in preview

Blazor Server is supported in ASP.NET Core 3.0. Blazor WebAssembly is in preview for ASP.NET Core 3.1.

This tutorial teaches the basics of building a real-time app using SignalR with Blazor WebAssembly. You learn how to:

  • Create a Blazor WebAssembly Hosted app project
  • Add the SignalR client library
  • Add a SignalR hub
  • Add SignalR services and an endpoint for the SignalR hub
  • Add Razor component code for chat

At the end of this tutorial, you'll have a working chat app.

View or download sample code (how to download)

Prerequisites

Create a hosted Blazor WebAssembly app project

Install the Blazor WebAssembly template. The Microsoft.AspNetCore.Blazor.Templates package has a preview version while Blazor WebAssembly is in preview. In a command shell, execute the following command:

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.2.0-preview1.20073.1

Follow the guidance for your choice of tooling:

  1. Create a new project.

  2. Select Blazor App and select Next.

  3. Type "BlazorSignalRApp" in the Project name field. Confirm the Location entry is correct or provide a location for the project. Select Create.

  4. Choose the Blazor WebAssembly App template.

  5. Under Advanced, select the ASP.NET Core hosted check box.

  6. Select Create.

Note

If you upgraded or installed a new version of Visual Studio and the Blazor WebAssembly template doesn't appear in the VS UI, reinstall the template using the dotnet new command shown previously.

Add the SignalR client library

  1. In Solution Explorer, right-click the BlazorSignalRApp.Client project and select Manage NuGet Packages.

  2. In the Manage NuGet Packages dialog, confirm that the Package source is set to nuget.org.

  3. With Browse selected, type "Microsoft.AspNetCore.SignalR.Client" in the search box.

  4. In the search results, select the Microsoft.AspNetCore.SignalR.Client package and select Install.

  5. If the Preview Changes dialog appears, select OK.

  6. If the License Acceptance dialog appears, select I Accept if you agree with the license terms.

Add a SignalR hub

In the BlazorSignalRApp.Server project, create a Hubs (plural) folder and add the following ChatHub class (Hubs/ChatHub.cs):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace BlazorSignalRApp.Server.Hubs
{
    public class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

Add SignalR services and an endpoint for the SignalR hub

  1. In the BlazorSignalRApp.Server project, open the Startup.cs file.

  2. Add the namespace for the ChatHub class to the top of the file:

    using BlazorSignalRApp.Server.Hubs;
    
  3. Add the SignalR services to Startup.ConfigureServices:

    services.AddSignalR();
    
  4. In Startup.Configure between the endpoints for the default controller route and the client-side fallback, add an endpoint for the hub:

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapDefaultControllerRoute();
        endpoints.MapHub<ChatHub>("/chatHub");
        endpoints.MapFallbackToClientSideBlazor<Client.Program>("index.html");
    });
    

Add Razor component code for chat

  1. In the BlazorSignalRApp.Client project, open the Pages/Index.razor file.

  2. Replace the markup with the following code:

@page "/"
@using Microsoft.AspNetCore.SignalR.Client
@inject NavigationManager NavigationManager

<div class="form-group">
    <label>
        User:
        <input @bind="_userInput" />
    </label>
</div>
<div class="form-group">
    <label>
        Message:
        <input @bind="_messageInput" size="50" />
    </label>
</div>
<button @onclick="Send" disabled="@(!IsConnected)">Send</button>

<hr>

<ul id="messagesList">
    @foreach (var message in _messages)
    {
        <li>@message</li>
    }
</ul>

@code {
    private HubConnection _hubConnection;
    private List<string> _messages = new List<string>();
    private string _userInput;
    private string _messageInput;

    protected override async Task OnInitializedAsync()
    {
        _hubConnection = new HubConnectionBuilder()
            .WithUrl(NavigationManager.ToAbsoluteUri("/chatHub"))
            .Build();

        _hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
        {
            var encodedMsg = $"{user}: {message}";
            _messages.Add(encodedMsg);
            StateHasChanged();
        });

        await _hubConnection.StartAsync();
    }

    Task Send() =>
        _hubConnection.SendAsync("SendMessage", _userInput, _messageInput);

    public bool IsConnected =>
        _hubConnection.State == HubConnectionState.Connected;
}

Run the app

  1. Follow the guidance for your tooling:
  1. In Solution Explorer, select the BlazorSignalRApp.Server project. Press Ctrl+F5 to run the app without debugging.

  2. Copy the URL from the address bar, open another browser instance or tab, and paste the URL in the address bar.

  3. Choose either browser, enter a name and message, and select the Send button. The name and message are displayed on both pages instantly:

    SignalR Blazor WebAssembly sample app open in two browser windows showing exchanged messages.

    Quotes: Star Trek VI: The Undiscovered Country ©1991 Paramount

Next steps

In this tutorial, you learned how to:

  • Create a Blazor WebAssembly Hosted app project
  • Add the SignalR client library
  • Add a SignalR hub
  • Add SignalR services and an endpoint for the SignalR hub
  • Add Razor component code for chat

To learn more about building Blazor apps, see the Blazor documentation:

Additional resources