AspNetCore.SignalR SendAsync 未在 OnConnectedAsync 内部触发

AspNetCore.SignalR SendAsync not firing inside OnConnectedAsync

我遇到了一个问题,我想在有人连接到集线器时向前端发送一个事件,但前端没有收到通知。我想我可能对直接从集线器调用方法与使用 IHubContext 调用方法感到困惑。我找不到太多与这些版本相关的信息,因此非常感谢您的帮助!

包版本:

Server side (.Net Core 2.2): Microsoft.AspNetCore.SignalR (1.1.0)
Client side (React): @aspnet/signalr:1.1.0

所以这是我的示例中心:

public class MyHub: Hub<IMyHub>
{
    public override async Task OnConnectedAsync()
    {
        // This newMessage call is what is not being received on the front end
        await Clients.All.SendAsync("newMessage", "test");

        // This console.WriteLine does print when I bring up the component in the front end.
       Console.WriteLine("Test");

        await base.OnConnectedAsync();
    }

    public Task SendNewMessage(string message)
    {
        return Clients.All.SendAsync("newMessage", message);
    }
}

现在,我目前的工作电话是在服务中,但它正在发送 "newMessage",如下所示:

public class MessageService: IMessageService
{
    private readonly IHubContext<MyHub> _myHubContext;

    public MessageService(IHubContext<MyHub> myHubContext)
    {
        _myHubContext = myHubContext;
    }

    public async Task SendMessage(string message)
    {
        // I noticed tis calls SendAsync from the hub context, 
        // instead of the SendMessage method on the hub, so maybe
        // the onConnectedAsync needs to be called from the context somehow also?
        await _myHubContext.Clients.All.SendAsync("newMessage", message);
    }
}

所以上面的服务方法调用有效并且会联系前端,这是我在反应组件中的前端连接的例子:

const signalR = require('@aspnet/signalr');

class MessageComponent extends React.Component {
    connection: any = null;

    componentDidMount() {
        this.connection = new signalR.HubConnectionBuilder()
            .withUrl('http://localhost:9900/myHub')
            .build();

        this.connection.on('newMessage', (message: string) => {
            // This works when called from the service IHubContext
            // but not OnConncectedAsync in MyHub
            console.log(message);
        });

        this.connection.start();
    }

    componentWillUnmount() {
        this.connection.stop();
    }

    render() {
        ...
    }
}

这是因为您使用的是强类型集线器 (https://docs.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-2.2#strongly-typed-hubs)。

我假设您在 IMyHub 接口上定义了 SendAsync,因此服务器正在发送带有 method = SendAsync, arguments = "newMessage", "test" 的消息。如果您删除了 IMyHub 类型,那么这将按预期工作。