@page "/chat" @using Microsoft.AspNetCore.SignalR.Client @inject IConfiguration Configuration @inject NavigationManager NavigationManager @implements IAsyncDisposable

Blazor SignalR Chat

@if (_hubConnection == null || _hubConnection.State != HubConnectionState.Connected) {
Connecting to server...
}
@foreach (var message in _messages) {
@message.User: @message.Text
}
@code { private HubConnection? _hubConnection; private List<(string User, string Text)> _messages = new(); private string _userInput = "User"; // Default username private string _messageInput = string.Empty; // Helper to check connection status private bool IsConnected => _hubConnection?.State == HubConnectionState.Connected; // The API URL where the SignalR Hub is hosted (must match the API project) private const string ApiUrl = "https://localhost:7056/chathub"; // <-- IMPORTANT: Update with your backend API URL and port protected override async Task OnInitializedAsync() { // 1. Initialize the HubConnection _hubConnection = new HubConnectionBuilder() .WithUrl(NavigationManager.ToAbsoluteUri(ApiUrl)) .Build(); // 2. Define the client method the server calls ("ReceiveMessage") _hubConnection.On("ReceiveMessage", (user, message) => { var isCurrentUser = user.Equals(_userInput, StringComparison.OrdinalIgnoreCase); var newMessage = (User: user, Text: message); // Add message to the list _messages.Add(newMessage); // Trigger UI update InvokeAsync(StateHasChanged); }); try { Console.WriteLine("ETT"); // 3. Start the connection await _hubConnection.StartAsync(); Console.WriteLine(_hubConnection.State); } catch (Exception ex) { // Log connection error Console.WriteLine($"Error connecting to SignalR Hub: {ex.Message}"); } } private async Task Send() { if (_hubConnection is not null && !string.IsNullOrWhiteSpace(_messageInput)) { try { Console.WriteLine("EEE"); Console.WriteLine(_hubConnection.State); await _hubConnection.SendAsync("SendMessage", _userInput, _messageInput); _messageInput = string.Empty; } catch (Exception ex) { Console.WriteLine($"Error sending message: {ex.Message}"); } } } private async Task HandleKeyUp(KeyboardEventArgs e) { // Allow sending message with the Enter key if (e.Key == "Enter") { await Send(); } } // Clean up connection when the component is disposed public async ValueTask DisposeAsync() { if (_hubConnection is not null) { await _hubConnection.DisposeAsync(); } } }