【问题标题】:AspNetCore.SignalR SendAsync not firing inside OnConnectedAsyncAspNetCore.SignalR SendAsync 未在 OnConnectedAsync 内触发
【发布时间】:2019-01-23 17:24:21
【问题描述】:

我有一个问题,我想在有人连接到集线器时向前端发送一个事件,但前端没有收到通知。我想我可能对直接从集线器调用方法与使用 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);
    }
}

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

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() {
        ...
    }
}

【问题讨论】:

  • 我怀疑 base.OnConnectedAsync 应该被称为 before Clients.All.SendAsync;它可能是将新客户端添加到Clients.All 的基本实现。

标签: asp.net-core signalr asp.net-core-2.0 signalr.client asp.net-core-signalr


【解决方案1】:

这是因为您使用的是强类型集线器 (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 类型,那么这将按预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    • 2018-06-19
    • 2013-05-25
    • 2015-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多