AspNetCore.SignalR SendAsync不在OnConnectedAsync内部触发

时间:2019-01-23 17:24:21

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

我遇到一个问题,当有人连接到集线器时,我想向前端发送事件,但是前端未收到通知。我认为直接从中心调用方法与利用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() {
        ...
    }
}

1 个答案:

答案 0 :(得分:1)

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

我假设您在resolve(data);界面上定义了SendAsync,因此服务器正在使用IMyHub发送消息。如果您删除了method = SendAsync, arguments = "newMessage", "test"类型,那么它将按预期工作。