ChatMessages.Add(message) is not hit

Viewed 52

I'm getting started with simple signalR application. When user puts his "name" and "room". It is sent to my hub

//This is Index page
public async Task<ActionResult> OnPost()
        {
            UserConnection userConnection = new()
            {
                Name = UserInput,
                Room = JoinRoomInput
            };

            await _hubConnection.SendAsync("JoinRoom", userConnection);
            return RedirectToPage("ChatGroup");
        }

my chat looks like this

public class ChatHub : Hub<IChatClient>
    {
        private readonly string _botUser;
        public ChatHub()
        {
            _botUser = "MyChat Bot";
        }
        public async Task JoinRoom(UserConnection userConnection)
        {
            await Groups.AddToGroupAsync(Context.ConnectionId, userConnection.Room);
            await Clients.Group(userConnection.Room).ReceiveMessage(_botUser, $"{userConnection.Name} has joined {userConnection.Room}");
        }
        public async Task SendMessage(UserConnection userConnection, string message)
        {
            await Clients.Group(userConnection.Room).ReceiveMessage($"{userConnection.Name} : ", message);
        }
    }

So then, the use posts his details and hit joinroom. He is redirected to another razor page called Chatgroup.In this page, He should get the message as defined in "JoinRoom" in ChatHub.

//This is Chatgroup page
private readonly HubConnection _hubConnection;
public List<string> ChatMessages { get; set; }
        public ChatGroupModel(HubConnection hubConnection)
        {
            _hubConnection = hubConnection;
        }
        public void OnGet()
        {
            _hubConnection.On<string>("ReceiveMessage", (message) => //Breakpoint hits here
            {
                ChatMessages.Add(message); // When placed a breakpoint here, It is skipped.
            });
        }

I'm getting ChatMessages is Null error. So my question is how will my client side code _hubConnection.On<> get the response from chathub? I think this is the issue. I've registered my signalr in startup class like this

services.AddTransient<HubConnection>((ChatClient) => {
                var hubConnection = new HubConnectionBuilder().WithUrl("https://localhost:44389/chathub").Build();
                hubConnection.Closed += async (error) =>
                    {
                        await Task.Delay(new Random().Next(0, 5) * 1000);
                        await hubConnection.StartAsync();
                    };
                hubConnection.StartAsync();
                return hubConnection;
            });

I get a null exception error in my razor page. I think it's because _hubConnection.On<>... skips chatmessage.add.

@foreach(var messages in Model.ChatMessages) //ChatMessages is Null
    {
        <div>
            @messages
        </div>
    }
0 Answers
Related