SignalR 集线器在调用方法后关闭连接

SignalR hub closes connection after method invoked

我使用带有非常基本的 Hub 的 net core 3.1 应用程序。一切都按预期在本地工作。但是在服务器上,websocket 连接在执行第一次调用后关闭。

我确定服务器上启用了 websockets。使用 Blazor Server 的另一部分工作正常。而且只要没有调用集线器方法,websocket 连接就处于活动状态。

客户端也接收到集线器发送的数据。

在chrome中测试,点击按钮后,警告框显示三个消息。然后连接丢失:

Uncaught (in promise) Error: Invocation canceled due to the underlying connection being closed.

我已经测试过从本地计算机使用客户端连接到服务器,但无法正常工作。所以这里应该不是客户端问题。

使用本地客户端和本地 运行 应用程序,一切正常。

TestHub.cs

using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;

namespace Test
{
    public class TestHub : Hub
    {
        public async Task Test(string name)
        {
            await Clients.Caller.SendAsync("Message", $"Hello, World! ({ name }) 1");
            await Clients.Caller.SendAsync("Message", $"Hello, World! ({ name }) 2");
            await Clients.Caller.SendAsync("Message", $"Hello, World! ({ name }) 3");
        }
    }
}

Index.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/3.1.7/signalr.min.js"></script>

<h1>Test</h1>
<button onclick="test()">Test</button>

<script>
    const connection = new signalR.HubConnectionBuilder()
        .withUrl("/Hub/Test")
        .configureLogging(signalR.LogLevel.Information)
        .build();

    function start() {
        try {
            connection.start();
            console.log("SignalR Connected.");
        } catch (err) {
            console.log(err);
            setTimeout(start, 5000);
        }
    };

    connection.on("Message", (message) => {
        alert(message);
    });

    function test() {
        try {
            connection.invoke("Test", "Foo");
        } catch (err) {
            alert(err);
        }
    }

    start();
</script>

引用 nuget Mongo2Go 导致了问题。在 3.1.3 版中,他们添加了 System.Text.Json 5.0.1,它破坏了信号器。

将 Mongo2Go 降级到版本 3.1.1 使信号器再次工作。