问题
This should be a simple question. I am trying to send complex objects to a client by id from a SignalR Hub. However, I can seem to find any examples that work with .NET Core 3.0.
Do I need to serialize it and call Clients.Client(id).BroadcastMessage("method",jsonString); ?
or is there a better way to do this?
回答1:
Note: This is tested only on ASP.NET Core 3.1 and may/may not work on older versions. You can pass multiple objects from C# and then receive them all in a Typescript function with a similar signature. For brevity, i am including only the relevant parts.
On server side (I used C#), you can use something like this to send a message (with multiple object parameters) to the client.
IHubContext<MessageHub> _hubContext;
_hubContext.Clients.All.SendCoreAsync(
"MethodName",
new object[] {someObject, someNumber, someString });
On client side (in Typescript), you would have something like this to receive all parameters.
// Configure the hub connection.
this.hubConnection = new HubConnectionBuilder()
.withUrl(hubUrl, { accessTokenFactory: () => myToken })
.withAutomaticReconnect()
.configureLogging(LogLevel.Error)
.build();
// Wire up an event handler to receive messages.
private registerEvent = (eventName: string, index: number) => {
this.hubConnection.on(eventName, this.alertHandler);
};
private alertHandler = (someObject: any, someNumber: number, someString: string) => {
console.log(someObject, someNumber, someString);
};
Hope this helps.
回答2:
I just found the answer. I had the hub as a generic so it couldn't find 'SendAsync' method. Remove the generic and it works great!
来源:https://stackoverflow.com/questions/58308621/sending-complex-objects-from-signalr-net-core-3-0-hub-to-clientin