如何将数据从ReactJs发送到signalR?在Asp.net Mvc Web Api中

问题描述

当我想将数据从React Component发送到集线器时出现问题我没有发送... 注意集线器已连接到客户端,但数据未发送/接收

集线器代码

public void SendMessagetoAll(string userName,string message)
        {
             Clients.All.messageReceived(userName,message );

        }

反应Js代码

import React,{ Component } from 'react';
import { Link } from 'react-router-dom';
import { hubConnection } from 'signalr-no-jquery';


class Dashboard extends Component {
   constructor(props) {    
   super(props);
   const connection = hubConnection('https://localhost:44332');
   const hubProxy = connection.createHubProxy('Chat');

   hubProxy.on('Hello',function(name) {
    console.log(name);
});
    // atempt connection,and handle errors
    connection.start()

    .done(function(){ console.log('Now connected,connection ID=' + connection.id); })
    .fail(function(){ console.log('Could not connect'); });
}


  render() {
    return (
        <div/>
    );
  }
}

export default Dashboard;

解决方法

通常,使用SignalR时,我们将创建ChatHub.cs,其中包含send / receive方法。在客户端,我们将声明一个代理以引用集线器并连接集线器,然后,我们可以调用集线器的send / receive方法来传输消息。但是从您的代码中,我找不到您在哪里调用“ SendMessageToAll()”方法,因此该消息将不会发送。请检查您的代码。

这里有一些有关使用SignalR的教程,您可以检查它们:

Chat Application Using ASP.NET,ReactJS,Web API,SignalR and Gulp

Tutorial: Real-time chat with SignalR 2