首页 > 解决方案 > WebSocket 连接到“ws://localhost:5000/notificationHub”失败:WebSocket 握手期间出错:意外响应代码:307

问题描述

我已经在我的角度客户端和 asp.netcore webapi 上实现了 signalR。目前我在客户端连接到服务器时收到以下错误

WebSocket connection to 'ws://localhost:5000/notificationHub' failed: Error during WebSocket handshake: Unexpected response code: 307

有人可以告诉我可能是什么问题。我已经在服务器端设置了 CORS。目前我正在为客户端使用端口 4021,因为我已经使用该端口为客户端提供服务。服务器在 5000 端口上可用

服务器代码

 public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddHostedService<DashboardHostedService>();
            services.AddControllers();
            services.AddCors(o => o.AddPolicy("CorsPolicy", builder => {
                builder
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                .WithOrigins("http://localhost:4201");
            }));
            services.AddSignalR();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            app.UseCors("CorsPolicy");
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<NotificationHub>("/notificationHub");
            });
        }
    }

角客户端

export class SignalrService {
  private message$: Subject<Message>;

  private connection: signalR.HubConnection;

  constructor() {
    this.message$ = new Subject<Message>();
    this.connection = new signalR.HubConnectionBuilder()
      .withUrl(environment.hubUrl, {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      .build();
    this.connect();
  }

  private connect(): void {
    if (this.connection.state === signalR.HubConnectionState.Disconnected) {
      this.connection.start().catch(err => console.log(err));
    }
  }
}

标签: angularasp.net-coresignalr

解决方案


根据您的代码和异常,您的 SignalR 集线器服务器似乎通过 HTTP (http://localhost:5000) 和 HTTPS (https://localhost:5001) 侦听和响应,并且您将应用程序配置为重定向 HTTP通过UseHttpsRedirectionStartup类中调用对 HTTPS 的请求。

如果您.withUrl("http://localhost:5000/notificationHub")在 Angular 客户端指定 URL,这将导致问题。

在此处输入图像描述

要修复它,您可以尝试修改代码以使用 HTTPS URL。

.withUrl("https://localhost:5001/notificationHub", {
  skipNegotiation: true,
  transport: signalR.HttpTransportType.WebSockets
})

app.UseHttpsRedirection();或者不通过从类Configure中的方法中删除来强制使用 HTTPS Startup


推荐阅读