通过 React 客户端应用程序连接到 Ocelot Api 网关中的 SignalR 集线器时未处理的拒绝(错误)(HttpError)

Unhandled Rejection (Error) (HttpError) when connecting to SignalR hub in Ocelot Api Gateway via React Client Application

我正在尝试从 React 应用程序连接到 Ocelot Api 网关后面的 SignalR 集线器。但是,这样做时出现以下错误:

Unhandled Rejection (Error): 
new HttpError
index.js:1 [2021-01-31T02:42:31.498Z] Error: Failed to complete negotiation with the server: Error
index.js:1 [2021-01-31T02:42:31.498Z] Error: Failed to start the connection: Error
Uncaught (in promise) Error
    at new HttpError (Errors.ts:20)
    at FetchHttpClient.<anonymous> (FetchHttpClient.ts:116)
    at step (FetchHttpClient.ts:2)
    at Object.next (FetchHttpClient.ts:2)
    at fulfilled (FetchHttpClient.ts:2)

我已经阅读了 Ocelot 关于 SignalR/WS (https://ocelot.readthedocs.io/en/latest/features/websockets.html) 的文档,并且还确保请求在我的 ocelot.json:

中按照应有的方式进行路由
    {
        "DownstreamPathTemplate": "/notificationhub",
        "DownstreamScheme": "ws",
        "DownstreamHostAndPorts": [
          {
            "Host": "localhost",
            "Port": 7001
          }
        ],
        "UpstreamPathTemplate": "/notifications",
        "UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ]
      },

怎么了?

首先,Ocelot 文档中没有提到的 web sockets secure (wss) 可以用作 sam9291 here 指出的 DownStreamScheme (https://github.com/ThreeMammals/Ocelot/issues/1179)。

其次,必须使用 AllowCredentials() 在 SignalR 应用程序上启用 Cors,如 Microsoft 此处所述 (https://docs.microsoft.com/en-us/aspnet/core/signalr/security?view=aspnetcore-5.0)。

第三,ocelot.json 中必须有一个 {catchAll} 路由,这是必要的,因为握手涉及 getting/posting 到其他路由:

    {
        "DownstreamPathTemplate": "/notificationhub/{catchAll}",
        "DownstreamScheme": "ws",
        "DownstreamHostAndPorts": [
          {
            "Host": "localhost",
            "Port": 7001
          }
        ],
        "UpstreamPathTemplate": "/notifications/{catchAll}",
        "UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ]
      },

第四,当我尝试在上述更改后请求 /notifications 时,我收到错误 404,不确定它是错误还是功能,例如 LilRazi 运行 问题到这里 (ocelot: 404 error when add extra path on upstream url ).所以我只是为 /notifications 部分添加了一条路线,如下所示:

    {
        "DownstreamPathTemplate": "/notificationhub",
        "DownstreamScheme": "ws",
        "DownstreamHostAndPorts": [
          {
            "Host": "localhost",
            "Port": 7001
          }
        ],
        "UpstreamPathTemplate": "/notifications",
        "UpstreamHttpMethod": [ "GET", "POST", "PUT", "DELETE", "OPTIONS" ]
      },

一切正常!