在 azure windows VM (C#/.NET5.0) 上托管服务时无法将 websocket 与 SignalR 一起使用

Can't use websocket with SignalR when hosting service on azure windows VM (C#/.NET5.0)

我有一个 .NET5.0 独立服务(作为 windows 服务安装),它启动一个基本的 SignalR 集线器。它使用 Http.Sys 内部有一些其他 API 控制器,我目前正在使用 HubConnection 从 WinForms 客户端连接到它。

它在我的开发机器上完美运行,但是当我将它移到 Azure VM(服务器 2019 数据中心)时,来自客户端的第一个 WebSocket 调用挂起一段时间,然后失败。从那时起它似乎“工作”了,但是非常非常慢(太慢而无法使用)。

我已经在 Azure 服务器和 Azure 门户中打开了适当的传入和传出端口。

如果我 运行 我的 Winforms 客户端在同一虚拟网络中的不同 azure VM 上,一切正常。因此,我确定服务器工作正常,只有当我通过互联网访问时才会失败。

当我尝试从外部连接时,服务器日志文件显示:

2021-11-24 17:10:19.6884|1|DEBUG|Microsoft.AspNetCore.SignalR.Internal.DefaultHubDispatcher|Received hub invocation: InvocationMessage { InvocationId: "1", Target: "GetAllState", Arguments: [ ], StreamIds: [ ] }. 17:10:31.1564|4|DEBUG|Microsoft.AspNetCore.Http.Connections.Internal.Transports.WebSocketsTransport|Waiting for the application to finish sending data. 2021-11-24 17:10:31.1564|12|DEBUG|Microsoft.AspNetCore.Http.Connections.Internal.Transports.WebSocketsTransport|Error writing frame. System.Threading.Tasks.TaskCanceledException: A task was canceled. at System.Net.WebSockets.ManagedWebSocket.SendFrameFallbackAsync(MessageOpcode opcode, Boolean endOfMessage, ReadOnlyMemory1 payloadBuffer, CancellationToken cancellationToken) at System.Net.WebSockets.WebSocketExtensions.SendMultiSegmentAsync(WebSocket webSocket, ReadOnlySequence1 buffer, WebSocketMessageType webSocketMessageType, CancellationToken cancellationToken) at Microsoft.AspNetCore.Http.Connections.Internal.Transports.WebSocketsServerTransport.StartSending(WebSocket socket) 2021-11-24 17:10:31.1564|2|DEBUG|Microsoft.AspNetCore.Http.Connections.Internal.Transports.WebSocketsTransport|Socket closed.

The client shows this:

2021-11-24 18:55:43.4679|50|ERROR|Microsoft.AspNetCore.SignalR.Client.HubConnection|The server connection was terminated with an error. System.Net.WebSockets.WebSocketException (0x80004005): The remote party closed the WebSocket connection without completing the close handshake. ---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.. ---> System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host.

我看了很多试图解决这个问题的文章,但找不到任何相关内容。它必须与配置相关,并且必须处于“azure 门户”级别,因为该服务跨 LAN 工作。有谁知道我需要做什么才能得到这个 运行ning?

更新:

我在新的自定义端口上使用 TcpListener 和 TcpClient 创建了几个控制台应用程序,运行 我的 Azure VM 上的服务器应用程序通过互联网成功连接到它,并在两者之间传递消息。非常困惑为什么 WebSocket 无法在互联网上工作。

更新2:

我将服务更改为使用 Kestrel,现在它可以按预期运行。因此,无论出于何种原因,它都拒绝使用 Http.Sys 在 Internet 上工作。我只是使用 Http.Sys 为一些不会使用此服务的其他客户端提供基本身份验证,因此 Kestrel 可以正常工作。

我将服务更改为使用 Kestrel,它现在可以正常工作了。因此,无论出于何种原因,它都拒绝使用 Http.Sys.

在互联网上工作