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

如何解决Angular连接HTTP部署的SignalR Hub时的混合内容错误

解决SignalR Hub混合内容连接问题

问题描述

客户端页面通过HTTPS(https://myDomain.ru/)加载,但请求的SignalR Hub资源使用HTTP协议,触发浏览器混合内容拦截,错误信息如下:

polyfills.e13fca6f3d31ac52.js:1 Mixed Content: The page at 'https://myDomain.ru/' was loaded over HTTPS, but requested an insecure resource 'http://myIp:5004/hub/negotiate?negotiateVersion=1'. This request has been blocked; the content must be served over HTTPS.

客户端连接代码:

export class AppComponent {
  title = 'cathrasisraw-client-app';
  private hubConnectionBuilder!: HubConnection;
  offers: string[] = [];
  ngOnInit(): void {
    this.hubConnectionBuilder = new HubConnectionBuilder()
      .withUrl('http://serverIp:5004/hub',{
        skipNegotiation: false,
      })
      .configureLogging(LogLevel.Information)
      .build();
    this.hubConnectionBuilder
      .start()
      .then(() => console.log('Connection started.......!'))
      .catch(err => console.log('Error while connect with server'));
    this.hubConnectionBuilder.on('SendMessageForUser', (result: any) => {
      this.offers.push(result);
    });
  }
}

解决方案

1. 给SignalR Hub配置HTTPS(生产环境推荐)

浏览器的混合内容安全策略禁止HTTPS页面加载HTTP资源,这是最彻底的解决方式:

  • Docker部署场景:生成SSL证书,启动容器时挂载证书文件,并配置ASP.NET Core启用HTTPS。可通过容器启动参数指定--https,或在appsettings.json中配置Kestrel的HTTPS端点,指定证书路径和密码。
  • 客户端修改连接地址为HTTPS协议,示例代码:
export class AppComponent {
  title = 'cathrasisraw-client-app';
  private hubConnectionBuilder!: HubConnection;
  offers: string[] = [];
  ngOnInit(): void {
    this.hubConnectionBuilder = new HubConnectionBuilder()
      // 替换为HTTPS协议的服务端地址
      .withUrl('https://serverIp:5004/hub',{
        skipNegotiation: false,
      })
      .configureLogging(LogLevel.Information)
      .build();
    this.hubConnectionBuilder
      .start()
      .then(() => console.log('连接已启动.......!'))
      .catch(err => console.log('连接服务器时出错:', err));
    this.hubConnectionBuilder.on('SendMessageForUser', (result: any) => {
      this.offers.push(result);
    });
  }
}

2. 开发环境临时绕过(生产环境禁用)

仅用于本地测试,可在浏览器中临时允许当前站点加载不安全内容:

  • Chrome:点击地址栏锁图标 → 选择「站点设置」→ 将「不安全内容」设为「允许」
  • Firefox:右键页面 → 「查看页面信息」→ 「权限」→ 修改「加载不安全内容」为允许

3. 反向代理统一协议

使用Nginx/Apache作为反向代理,客户端通过HTTPS访问代理,代理再转发请求到后端HTTP的SignalR Hub:

  • Nginx配置示例(需提前配置SSL证书):
server {
    listen 443 ssl;
    server_name myDomain.ru;

    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;

    location /hub {
        proxy_pass http://serverIp:5004/hub;
        # 支持WebSocket转发(SignalR依赖)
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;
    }
}
  • 客户端连接地址改为https://myDomain.ru/hub,无需直接访问服务器IP和端口。

内容的提问来源于stack exchange,提问作者Александр Окостень

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 19:15:59