我正在开发一个 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/