首页 > 解决方案 > SignalR 集线器在 WebSocket 握手期间返回错误:意外的响应代码:302 Net Core Angular 和 Azure

问题描述

我有一个角度应用程序,它通过 SignalR 连接到 Net Core 以获取信息。本地运行完美,但是当应用程序执行来自 Azure 的请求时会抛出此错误

WebSocket 连接到“wss://mysite.azurewebsites.net/notifications?id=someId&access_token=sometoken”失败:WebSocket 握手期间出错:意外响应代码:302 错误:无法启动传输“WebSockets”:未定义

但仍在返回数据并进行连接并带来信息,只是控制台上出现烦人的错误

这是我对 signalR 的 Angular Side 调用

  private createConnection() {
this.hubConnection = new signalR.HubConnectionBuilder()
                            .withUrl(`${this.libraryConfig.api.notification.baseUrl}/notifications`, { accessTokenFactory: () => this.access_token })
                            .build(); 
  }

这是我在 Net Core 上启动的代码

services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(options =>
            {
                options.Authority = "https://sts.windows.net/tenat/v2.0";
                options.Audience = Configuration.GetSection("AzureAd").GetSection("Audience").Value;
                options.TokenValidationParameters.ValidateLifetime = true;
              options.Events = new JwtBearerEvents
                {
                    OnMessageReceived = context =>
                    {
                        var accessToken = context.Request.Query["access_token"];

                        // If the request is for our hub...
                        var path = context.HttpContext.Request.Path;
                        if (!string.IsNullOrEmpty(accessToken) &&
                                (path.StartsWithSegments("/notifications")))
                        {
                            // Read the token out of the query string
                            context.Token = accessToken;
                        }
                        return Task.CompletedTask;
                    }
                };

            });

我一直在尝试我能找到的所有解决方案,但没有任何效果。

注意:我使用 Azure Active Directory 登录客户端

标签: angularazure.net-coreazure-active-directorysignalr-hub

解决方案


您需要在 Azure 应用服务中启用 Websocket。它在配置->常规设置下


推荐阅读