SignalR Websockets not working and stuck on “pending”

  Kiến thức lập trình

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.

LEAVE A COMMENT