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

Angular8连接AspNet.SignalR Hub时遭遇CORS错误求助

Angular8连接SignalR Hub时的CORS问题排查

我正尝试在Angular8中创建服务,连接Visual Studio调试环境下的SignalR Hub。由于Angular8部署在不同域名下,我按照相关建议,在SignalR的startup.cs中添加了CorsOptions.AllowAll配置:

using Microsoft.AspNet.SignalR;
using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Owin;

[assembly: OwinStartup(typeof(SignalRChat.Startup))]
namespace SignalRChat
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Map("/signalr", map =>
            {
                map.UseCors(CorsOptions.AllowAll);
                var hubConfiguration = new HubConfiguration { };
                map.RunSignalR(hubConfiguration);
            });
        }
    }
}

但当Angular8服务尝试连接服务器时,*预请求(Preflight)*抛出了CORS错误。
CORS Error on connection.start()

以下是我用于与SignalR通信的Angular服务代码片段,注意此处导入的是signalr,但使用@aspnet/signalr或@microsoft/signalr时会出现相同错误:

import { Component, Injectable, OnInit } from '@angular/core';
import * as signalR from 'signalr';
import { Subject } from 'rxjs';
import { ChatMessage } from './chat.model';

@Injectable()
export class ChatService implements OnInit {

    private connection: signalR.HubConnection;
    connectionEstablished = new Subject<Boolean>();
    receiverSubscription = new Subject<String>();
  
  constructor() { }

  ngOnInit(): void {
  }
 
  connect() {
    if (!this.connection) {
      this.connection = new signalR.HubConnectionBuilder()
      .withUrl('https://localhost:44323/signalr')
      .configureLogging(signalR.LogLevel.Debug)
      .build();
 
      this.connection.start().then(() => {
        console.log('Hub connection started');
        this.connectionEstablished.next(true);
      }).catch(err => console.log(err));
 
      this.connection.on('SendChat', (chatMessage) => {
        console.log('Received', chatMessage);
        this.receiverSubscription.next(chatMessage);
      });
     }
}

奇怪的是,当我使用部署在同一外部域名下的jQuery客户端测试时,并未出现该错误。我注意到一个差异:jQuery会在negotiate URL中添加一些参数,而Angular不会:
Successful call to 'negotiate' from jQuery

请问我遗漏了什么?或者该如何调试这个问题?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 19:25:25