1

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.