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.

services.AddSignalR();

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

  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
           

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapHub<ChatHub>("/chatHub");
                endpoints.MapFallbackToPage("/_Host");
            });
        }

 

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

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

<hr />

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

@code {
    HubConnection hubConnection;
    List<string> messages = new List<string>();
    string userInput;
    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 + " says " + message;
            messages.Add(encodedMsg);
            StateHasChanged();
        });

        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.