auburg
auburg

Reputation: 1475

Azure SignalR Blazor app not receiving messages

I'm looking at incorporating Azure SignalR functionality into my .net core Blazor web application. To this end i've been following this tutorial - Azure Signalr Serverless. This is working fine - i have a project running the Azure functions app and can start up two browsers and have a chat session. What i'm trying to do is add the ability to receive these message notifications from the Azure signalR hub that's been configured into my Blazor app. I've added the following code in Index.razor.cs that mimics the javascript code in the example client:

public class IndexComponent : ComponentBase
{
    private HubConnection _connection;

    public string Message;

    protected override Task OnInitializedAsync()
    {
        _connection = new HubConnectionBuilder()
            .WithUrl("http://localhost:7071/api")
            .Build();

        _connection.On<string, string>("ReceiveMessage", (user, message) =>
        {
            Message = $"Got message {message} from user {user}";
            this.StateHasChanged();
        });

        _connection.StartAsync();

        return base.OnInitializedAsync();
    }
}

The example javascript code btw is:

const connection = new signalR.HubConnectionBuilder()
  .withUrl(`${apiBaseUrl}/api`)
  .configureLogging(signalR.LogLevel.Information)
  .build();

connection.on('newMessage', newMessage);
connection.onclose(() => console.log('disconnected'));

console.log('connecting...');
connection.start()
  .then(() => data.ready = true)
  .catch(console.error);

So the problem is that my Blazor app never receives any message notifications sent from the javascript chat clients (so the _connection.On handler is never hit). What am i missing in my Blazor code ?

Upvotes: 0

Views: 1124

Answers (1)

auburg
auburg

Reputation: 1475

Ok so this is what i needed to do to get it to work in my Blazor app:

_connection.On<object>("newMessage", update =>
        {
            Console.WriteLine(update);
            //Message = update;
        });

I needed to subscribe to the 'newMessage' target (since that's the JS is sending on) and also the type that's being posted isn't a string but a JObject type which i would need to deserialize to the correct type.

Upvotes: 4

Related Questions