Popular blog tags

ASP.NET Core Blazor 3.x(Server-side)-Integrating ASP.NET Core SignalR chat

step 1:Create an ASP.NET Core Blazor(Server-side) Web app.


step2.In the Server project, add the following Hub/ChatHub.cs class.

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);

step 3.In the Server project, add the SignalR services in the Startup.ConfigureServices method.


step 4.Also add an endpoint for the ChatHub in Startup.Configure.

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

            app.UseEndpoints(endpoints =>


step 5:Add the ASP.NET Core SignalR Client package to the  project.

cd BlazorSignalRApp
dotnet add Client package Microsoft.AspNetCore.SignalR.Client

step 6.Update Pages/Index.razor in the Client project with the following markup.

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

    <label for="userInput">User:</label>
    <input id="userInput" @bind="userInput" />
<div class="form-group">
    <label for="messageInput">Message:</label>
    <input id="messageInput" @bind="messageInput" />
<button @onclick="Send" disabled="@(!IsConnected)">Send Message</button>

<hr />

<ul id="messagesList">
    @foreach (var message in messages)

@code {
    HubConnection hubConnection;
    List<string> messages = new List<string>();
    string userInput;
    string messageInput;

    protected override async Task OnInitializedAsync()
        hubConnection = new HubConnectionBuilder()

        hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
            var encodedMsg = user + " says " + message;

        await hubConnection.StartAsync();

    Task Send() => hubConnection.SendAsync("SendMessage", userInput, messageInput);

    public bool IsConnected => hubConnection.State == HubConnectionState.Connected;

step 7:Build and run the Server project

cd Server
dotnet run

step 8:Open the app in two separate browser tabs to chat in real time over SignalR.