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

.NET Aspire环境下SignalR无法通过WSS连接问题求助

.NET Aspire中启用SignalR WSS协议的必要配置

迁移到.NET Aspire后SignalR的WSS连接无响应,需要在Aspire Host及相关服务中做以下配置:

1. 确保API服务在Aspire中启用HTTPS

Aspire默认可能为服务分配HTTP端口,需显式指定HTTPS端点,同时确保本地开发证书已信任:

  • 在Aspire AppHost项目的Program.cs中注册API服务时指定HTTPS:
    var apiService = builder.AddProject<Projects.YourApiService>("your-api")
        .WithHttpsEndpoint(port: 5001, scheme: "https") // 自定义HTTPS端口
        .WithReference(bffService);
    
  • 信任本地开发证书:执行命令 dotnet dev-certs https --trust

2. 配置SignalR的跨域策略

API服务中必须允许前端Origin的跨域请求,且开启凭据支持(WSS连接依赖):

  • 在API的Program.cs中添加CORS策略:
    builder.Services.AddCors(options =>
    {
        options.AddPolicy("SignalRCorsPolicy", policy =>
        {
            policy.WithOrigins("https://localhost:5173") // Vue前端的HTTPS地址
                  .AllowAnyHeader()
                  .AllowAnyMethod()
                  .AllowCredentials() // 必须启用,WSS连接需要携带凭据
                  .WithMethods("GET", "POST");
        });
    });
    
    // 注意:UseCors必须在UseRouting和UseEndpoints之间
    app.UseCors("SignalRCorsPolicy");
    app.MapHub<YourMessageHub>("/messageHub"); // 映射SignalR Hub路由
    

3. 处理BFF反向代理的WSS转发(如果通过BFF访问API)

如果Vue前端通过BFF访问SignalR Hub,需配置Yarp反向代理支持WebSockets:

  • 在BFF的Program.cs中添加反向代理服务:
    builder.Services.AddReverseProxy()
        .LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"));
    
  • 在BFF的appsettings.json中配置路由,启用WebSockets元数据:
    "ReverseProxy": {
      "Routes": {
        "signalrRoute": {
          "ClusterId": "apiCluster",
          "Match": {
            "Path": "/messageHub/{**catch-all}"
          },
          "Metadata": {
            "AllowWebSockets": "true" // 显式启用WebSocket支持
          }
        },
        "apiRoute": {
          "ClusterId": "apiCluster",
          "Match": {
            "Path": "/api/{**catch-all}"
          }
        }
      },
      "Clusters": {
        "apiCluster": {
          "Destinations": {
            "api1": {
              "Address": "https://localhost:5001" // API服务的HTTPS地址
            }
          }
        }
      }
    }
    

4. 验证客户端连接配置

Vue客户端需使用正确的HTTPS/WSS地址建立连接,且启用凭据:

import { HubConnectionBuilder } from '@microsoft/signalr';

const hubConnection = new HubConnectionBuilder()
  .withUrl('https://localhost:5001/messageHub', { // 或BFF的代理地址,如https://localhost:5000/messageHub
    withCredentials: true
  })
  .withAutomaticReconnect()
  .build();

// 启动连接并监听消息
hubConnection.start()
  .then(() => console.log('SignalR连接成功'))
  .catch(err => console.error('连接失败:', err));

hubConnection.on('ReceiveMessage', (message) => {
  console.log('收到消息:', message);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:15:10