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

SignalR无法从JS客户端连接到ASP.NET Core 7服务器求助

ASP.NET Core 7 gRPC+SignalR通知服务连接失败排查

我基于gRPC模板构建了ASP.NET Core 7通知服务(属于微服务项目),需要同时支持gRPC通信与SignalR客户端通知功能。搭建基础JS客户端测试时出现连接失败问题,试过.NET Web应用、React应用等客户端都无效,推测问题出在服务端。已经尝试启用Windows WebSocket功能、移除授权、参照官方文档配置等多种方案,还是没解决。

服务端Program.cs代码

using notification_service.Hubs;
using notification_service.messaging.Configuration;

var AllowedOriginsPolicy = "allowedOriginsPolicy";

var builder = WebApplication.CreateBuilder(args);

// Additional configuration is required to successfully run gRPC on macOS.
// For instructions on how to configure Kestrel and gRPC clients on macOS, visit https://go.microsoft.com/fwlink/?linkid=2099682

// Bson congifuration
BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));

// Add services to the container.
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(builder =>
    {
        builder.WithOrigins("http://localhost:5500", "http://localhost:5272", "http://localhost:3000")
               .AllowAnyHeader()
               .AllowAnyMethod()
               .AllowCredentials();
    });
});
builder.Services.AddGrpc();
builder.Services.AddNotificationDbSettings(builder.Configuration);
builder.Services.Configure<NatsConfig>(builder.Configuration.GetSection("NatsConfiguration"));
builder.Services.Configure<NotificationNatsConfig>(builder.Configuration.GetSection("NotificationNatsConfig"));
builder.Services.AddGrpcChannelOptions();
builder.Services.Configure<ServicesConfig>(builder.Configuration.GetSection("Services"));
builder.Services.AddAuth();
builder.Services.AddSignalR();
builder.Services.AddServices();
builder.Services.AddHostedServices();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseWebSockets();

app.UseAuthentication();
app.UseAuthorization();

app.UseCors();

app.Urls.Add($"http://localhost:{app.Configuration["NOTIFICATION_SERVICE_ADDRESS"]}" ?? "http://localhost:12009");

app.MapGet("/", () => "Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client, visit: https://go.microsoft.com/fwlink/?linkid=2086909");
app.MapHub<NotificationHub>("/hubs/notification");

客户端JS代码

import * as signalR from '@microsoft/signalr';

const SinglarTest = () => {
  let connection = new signalR.HubConnectionBuilder()
    .withUrl("http://localhost:12009/hubs/notification", {
      skipNegotiation: true,
      transport: signalR.HttpTransportType.WebSockets
    })
    .build();

  connection.start()
    .then(() => { console.log("Connection established")})
    .catch((err) => { console.log(err); });

  connection.on("notification", (data) => {
    console.log('data: ', data);
  })
}

export default SinglarTest;

排查建议

  • 调整中间件顺序:当前UseWebSockets放在UseCors之前,正确顺序应为UseRouting → UseCors → UseAuthentication → UseAuthorization → UseWebSockets,确保跨域规则先生效后再处理WebSocket请求。
  • 验证端口配置:确认NOTIFICATION_SERVICE_ADDRESS配置的端口确实是12009,可暂时硬编码端口测试,排除配置读取错误。
  • 关闭HTTPS重定向:客户端用HTTP连接,但服务端启用了UseHttpsRedirection,会将HTTP请求重定向到HTTPS,直接导致WebSocket连接失败,测试阶段可注释掉该中间件。
  • 检查Hub类实现:确保NotificationHub继承自Hub,无自定义授权逻辑或构造函数错误,基础实现示例:
    public class NotificationHub : Hub
    {
        // 无额外错误逻辑的基础实现
    }
    
  • 启用详细日志:在服务端添加日志配置,查看连接失败的具体细节:
    builder.Logging.AddConsole();
    builder.Logging.SetMinimumLevel(LogLevel.Debug);
    
  • 关闭跳过协商:测试阶段先移除skipNegotiation: true,让SignalR自动协商传输方式,排查是否为WebSocket直接连接的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:07:45