Search code examples
c#fluttersignalr

Flutter not receiving SignalR messages from C# Web API


I have a C# backend app and a Flutter frontend. In my backend I have a SignalR service that I want to consume in my Flutter app. My backend setup:

public class DangerReportHub : Hub
{
    public async Task SendDangerReport(object message)
    {
        // Broadcast the danger report to all connected clients
        await Clients.All.SendAsync("ReceiveDangerReport", message);
    }
}

Then I have the cors policy:

        services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
        {
            builder
                .AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod()
                .SetIsOriginAllowed((host) => true);
        }));

and then registering the hub:

        app.UseEndpoints(x =>
        {
            x.MapControllers();
            x.MapHub<DangerReportHub>("/dangerReportHub");
        });

in my web api call I have the following post method:

    [HttpPost]
    public async Task<IActionResult> ReportDanger([FromBody] DangerPostDTO dangerPostDTO)
    {
        var danger = await _dangerService.ReportDanger(dangerPostDTO.dangerId, dangerPostDTO.userId, dangerPostDTO.Location);
        if (danger.Data)
        {
            var dangerSignalR = new DangerSignalRDTO
            {
                DangerId = dangerPostDTO.dangerId,
                TimeReported = DateTime.Now.ToUniversalTime(),
                ReportedBy = dangerPostDTO.userId,
                Location = dangerPostDTO.Location
            };
            await _hubContext.Clients.All.SendAsync("ReceiveDangerReport", dangerSignalR);

            return Ok();
        }
        return BadRequest(danger.ErrorMessages);
    }

then in my flutter app I am trying to consume this signalr core using signalr_netcore package. and this is my setup:

  Future<void> _initHubConnection() async {
    // The location of the SignalR Server.
    const serverUrl = "http://*.*.*.*/dangerReportHub"; // IP is hidden for this question only
// Creates the connection by using the HubConnectionBuilder.
    final hubConnection = HubConnectionBuilder()
        .withUrl(serverUrl)
        .withAutomaticReconnect()
        .build();
    hubConnection.onclose(({Exception? error}) => print(error.toString()));
    await hubConnection.start();
    hubConnection.on("ReceiveDangerReport", _handleAClientProvidedFunction);
  }

  void _handleAClientProvidedFunction(dynamic? parameters) {
    debugPrint(parameters.toString());
    return null;
  }

so the strange thing is, when I execute a test call from a signalr test client for example https://gourav-d.github.io/SignalR-Web-Client/dist/ and I call directly SendDangerReport from the hub, it works. But when I call the WEB API call the Flutter client is not receiving the message. What might be wrong?


Solution

  • The problem was the Location property. It was a complex property that was not begin serialized.