Darryl Wagoner WA1GON
Darryl Wagoner WA1GON

Reputation: 1029

Sending complex objects from signalR .NET Core 3.0 hub to clientIn

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?

Upvotes: 1

Views: 2802

Answers (2)

James Poulose
James Poulose

Reputation: 3833

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.

Upvotes: 2

Darryl Wagoner WA1GON
Darryl Wagoner WA1GON

Reputation: 1029

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!

Upvotes: 0

Related Questions