c# - 如何使用 signalr 将 json 对象发送到 .net 服务器

标签 c# angular typescript asp.net-core signalr

我正在开发一个 Angular 应用程序,我必须使用 .netcore 服务器和 signalR 将数据从 Angular 形式发送到外部服务器。我可以使用信号集线器在 Angular 客户端和 Controller 之间建立连接,但我很困惑如何将 json 对象从客户端发送到 Controller 。我想从 Controller 将 Json 对象发送到外部服务器。我想使用信号器来实现这一点,因为我希望外部服务器和客户端之间进行实时通信。当我提交数据并收到来自外部服务器的响应时,我想提醒客户端。我正在寻找一些关于如何实现这一点的指导。

Angular 客户端

_hubConnection: HubConnection;
 transportType = signalR.HttpTransportType.LongPolling;

ngOnInit() {
   this._hubConnection = new signalR.HubConnectionBuilder()
    .configureLogging(signalR.LogLevel.Information)
    .withUrl("http://localhost:5000/message", this.transportType)
    .build();
}

fun1(){
 this._hubConnection.on("Send", (user, message) => {
  const received = `name: ${user}, message: ${message}`;
  console.log(received);
});

this._hubConnection.start()
    .then(() =>
        this._hubConnection.invoke('Send', "rk", "wassup").catch(function (err) {
        console.error(err.toString());
    })
)
.then(() =>
    console.log('connected')
)
.then(() => this._hubConnection.stop())
.then(() => console.log('Disconnected'))
.catch(e => console.error(e.message));

Controller

namespace ang.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class DistController : Controller
    {
        private IHubContext<DistHub> _hubContext;
        public DistController(IHubContext<DistHub> hubContext)
        {
            _hubContext = hubContext;
        }
    }
}

信号Rhub

namespace ang.HubConfig
{
    public class DistHub: Hub
    {
        public async Task Send (string user , string message)
        {
            // return Clients.All.SendAsync("Send", message);
            await Clients.All.SendAsync("Send", user, message);
        }
    }
}

启动.cs

app.UseSignalR(routes =>
{
    routes.MapHub<DistHub>("/message");
});

json 对象

const Root = {
  "Unit" : "mm",
  "test": [{
    "Val": this.Val1.isChecked,
    'Val1' : this.val2.isChecked,
  }],
  "test1" :{
    "sub":[{
      'val2' : this.valFormGroup.get('val2').value,
      'Val3' : this.valFormGroup.get('val3').value,
    }]
  },
}

最佳答案

您可以通过将根数据传递给调用来执行此操作

connection.invoke('Send', "rk", "wassup", Root);

然后在您的中心为根数据添加另一个参数

public async Task Send (string user , string message, string root)
{
  await Clients.All.SendAsync("Send", user, message);
}

更新,因为您提交了可以使用的 json 字符串

JsonConvert.DeserializeObject<List<object>>(root);

关于c# - 如何使用 signalr 将 json 对象发送到 .net 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58093494/

相关文章:

Typescript 扩展第三方类错误 : ElementHandle only refers to a type, 但在此处用作值

c# - 3 层应用程序架构中的域层是否应该包装 UI 层所需的数据层类?

c# - 数据注释上的正则表达式在子属性上的行为不同

angular - Angular 5 上的单元测试 http 服务

angularjs - 使用 webpack 和 typescript 摇树

typescript - 你如何在 Angular2 中对 NgFor 的结果运行一个函数?

c# - 如何在资源 api 中使用 IdentityServer4 范围

c# - 在 PayPal sdk 中调用 Payment.Create 时出现服务器不可用错误

javascript - Angular - 如何在组件级别实现异常处理

javascript - TypeScript - 如果扩展其他内容,则类泛型类型太窄,如果不扩展任何内容则不是