【问题标题】:SignalR client not receiving messages in integration testsSignalR 客户端未在集成测试中接收消息
【发布时间】:2021-07-29 07:42:29
【问题描述】:

我正在尝试在我的集成测试中测试我的 SignalR 连接。
客户端是这样的:

var connection = new HubConnectionBuilder()
                     .WithUrl(
                        $"{client.BaseAddress}meeting-notifications",
                         o =>
                         {
                             o.HttpMessageHandlerFactory = _ => Server?.CreateHandler();
                         })
                     .Build();

connection.On<BoardDto>("BoardStateChanged", board => { Do Something... });

await connection.StartAsync();

我在我的 ASP-NET Core 后端调用该方法,如下所示:

public async Task BroadcastBoardStateAsync(int boardId, BoardDto board)
{
    await _notificationHub.Clients.All.BoardStateChanged(board);
}

客户端可以调用服务器上的方法,但不能反过来。
有人知道我在这里缺少什么吗?

编辑:我调试了服务器调用,_notificationHub 包含客户端的连接 ID。

【问题讨论】:

  • 你为什么要分配HttpMessageHandlerFactory?代码的编写方式,如果Server 为null,则不会有任何处理程序。您是否尝试过没有选项回调的代码?您可以处理连接的事件以查看是否由于某种原因断开连接
  • 抱歉,如果不清楚。 Server 是运行集成测试的 TestServer。需要此调用,因为没有它,客户端的连接将被拒绝。

标签: c# asp.net-core signalr


【解决方案1】:

原来 SignalR v3.x 通过 System.Text.Json 进行 json 序列化,这对我的 POCO's 有一些问题。
为了解决这个问题,我必须通过这个方法调用明确告诉 SignalR 使用 NewtonsoftJson 进行序列化:

var connection = new HubConnectionBuilder()
                     .WithUrl(
                         $"{client.BaseAddress}meeting-notifications",
                         o =>
                         {
                             o.HttpMessageHandlerFactory = _ => Server?.CreateHandler();
                         })
              ---->  .AddNewtonsoftJsonProtocol()
                     .Build();

【讨论】:

  • 哇,我用这个拉了几个小时的头发。也为我工作。
猜你喜欢
  • 2013-05-21
  • 2020-08-13
  • 2017-05-26
  • 2019-09-27
  • 2021-10-18
  • 2016-08-25
  • 2020-10-15
  • 1970-01-01
  • 2016-04-29
相关资源
最近更新 更多