@page "/chat"
@using Microsoft.AspNetCore.SignalR.Client
@inject IConfiguration Configuration
@inject NavigationManager NavigationManager
@implements IAsyncDisposable
@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