You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SignalR WebSocket连接停滞pending,ASP.NET Razor聊天功能求助

ASP.NET Razor + SignalR 聊天请求Pending无响应问题排查

我正在构建基于ASP.NET Razor的基础网站,计划用SignalR WebSocket实现聊天功能,但运行后无任何反应。浏览器开发者工具网络面板显示请求处于pending状态,截图如下:
SignalR请求Pending截图

相关代码

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();
});

排查与解决步骤

1. 核对CORS配置与站点实际端口

CORS规则里指定的http://localhost:7241必须和站点实际运行端口完全一致。打开Properties/launchSettings.json确认站点的HTTP/HTTPS端口,把WithOrigins里的地址替换成实际值,比如:

builder.WithOrigins("https://localhost:7041", "http://localhost:5241")
       .AllowAnyHeader()
       .AllowAnyMethod()
       .AllowCredentials();

开发环境可临时用.AllowAnyOrigin()测试(生产环境禁用)。

2. 适配SignalR连接的协议与域名

如果站点启用了HTTPS重定向,前端硬编码/chatHub可能会用HTTP发起请求,导致重定向阻塞。改成自动适配当前站点的协议和域名:

var connection = new signalR.HubConnectionBuilder()
    .withUrl(window.location.origin + "/chatHub")
    .build();

3. 检查前端DOM元素是否存在

打开浏览器控制台(F12)查看是否有Cannot set property 'disabled' of null这类错误,确保Razor页面中存在id="sendmsg"、id="msgtxt"、id="chat-container"这三个元素。

4. 启用SignalR日志排查细节

在Program.cs中添加日志过滤,查看请求阻塞的具体原因:

builder.Logging.AddFilter("Microsoft.AspNetCore.SignalR", LogLevel.Debug);
builder.Logging.AddFilter("Microsoft.AspNetCore.Http.Connections", LogLevel.Debug);

运行站点后查看控制台输出的日志信息。

5. 确保SignalR客户端与服务端版本匹配

检查服务端NuGet包Microsoft.AspNetCore.SignalR的版本,前端引用的@microsoft/signalr包版本必须与之完全一致,版本不匹配会导致连接失败。

内容的提问来源于stack exchange,提问作者Kaloyan056

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 11:32:05