asp.net-corewebsocketrazor-pagesasp.net-core-signalr

SignalR Websockets not working and stuck on "pending"


I'm trying to build a basic ASP.NET Razor website that uses SignalR websockets for a chat. But when I run it nothing happens. I've attached what I get in the network tab in inspect element. enter image description here. Here are the Hub, Program.cs, and chat.js:

(Hub)

using Microsoft.AspNetCore.SignalR;

namespace WebApplication1
{
    public sealed class ChatHub : Hub
    {
        public async Task SendMessage(string user, string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", user, message);
        }
    }
}

(Program.cs)

using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);
            // Add services to the container.
            builder.Services.AddSignalR();
            builder.Services.AddRazorPages();
            builder.Services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.WithOrigins("http://localhost:7241")
                           .AllowAnyHeader()
                           .AllowAnyMethod()
                           .AllowCredentials();
                });
            });

            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (!app.Environment.IsDevelopment())
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
          

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseCors();
            app.UseAuthorization();
            app.MapRazorPages();
            app.MapHub<ChatHub>("/chatHub");
            app.Run();
        }
    }
}

(chat.js)

"use strict";

var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();

//Disable the send button until connection is established.
document.getElementById("sendmsg").disabled = true;

connection.on("ReceiveMessage", function (user, message) {
    
        var li = document.createElement("li");
        document.getElementById("chat-container").appendChild(li);
        li.textContent = `${user}: ${message}`;
    
    
});

connection.start().then(function () {
    document.getElementById("sendmsg").disabled = false;
}).catch(function (err) {
    return console.error(err.toString());
});

document.getElementById("sendmsg").addEventListener("click", function (event) {
    var user = localStorage["usernameT"];
    var message = document.getElementById("msgtxt").value;
    connection.invoke("SendMessage", user, message).catch(function (err) {
        return console.error(err.toString());
    });
    event.preventDefault();
});

I've tried everything that I can think of. Can someone please help me? I can attach more info if needed.


Solution

  • There are 2 points I want to share with you.


    The first, make sure there is no javascript error when using chat.js file in your your code, I found error in the console tab. You can verify it in your side.

    enter image description here

    And I can reproduce the issue like yours. If there is javascript error, please use official sample code. Add SignalR client code.

    enter image description here


    The second, if there is no issue in your code and the chat feature is working in your project. After investigation, this pending state is normal and expected behavior.

    enter image description here

    enter image description here

    enter image description here

    And here is detailed explanation (Content Download.).

    As we know signalr support websocket,sse,and longpolling. The default protocal is websocket. I will always send heart beat(type 6 msg) like below.

    So the pending state is normal, we just need to focus on the custom signalr features(like: chat, notification) are normal.

    enter image description here