androidasp.net-core-signalr

Andoird Cannot connect to SignalR running on Blazor Server


I am trying to connect to a .net 6 Core Blazor WASM core hosted using android.

String hubUrl = "http://192.168.254.173:5050/notification?parameter=1010072";
if (isReachable) {
    hubConnection = HubConnectionBuilder.create(hubUrl).build();
    if (hubConnection.getConnectionState() != HubConnectionState.CONNECTED) {
        hubConnection.start();
        hubConnection.on("MessageModelToClients", (messageModel) -> {
            Log.i("TAG", messageModel.getMessage());
        }, MessageModel.class);
        if (hubConnection.getConnectionState() == HubConnectionState.CONNECTED) {
            Log.i("TAG", "Connected");
        } else {
            Log.e("TAG", "Failed to establish connection to SignalR hub.");
        }
    }
} else {
    System.out.println("IP address is not reachable.");
}

this is my gradle,

implementation ("com.microsoft.signalr:signalr:7.0.0")

This is my Hub on the Core Hosted Blazor WASM

public class NotificationHub : Hub 
{
    ....
    
    public override async Task OnConnectedAsync()
    {
        Console.WriteLine("Connecting...");
        var userId= Context.GetHttpContext()!.Request.Query["userid"];
        var connectionId = Context.ConnectionId;
        AddUser(connectionId, userId);
        var messageModel = new MessageModel
        {
            IsPrivate = false,
            Message = $"Logged in User: {userId}",
            Recipient = string.Empty,
            Sender = SERVER_NAME
        };
        await SendConnectedUsers();
        await SendObjectToAll(messageModel);

        Console.WriteLine($"CONNECTED: {connectionId}");

        await base.OnConnectedAsync();
    }
    
    
    ...
}

In the Program.cs

builder.Services.AddSignalR();
app.UseEndpoints(endpoints =>
{
    endpoints.MapHub<NotificationHub>("/notification");
});

Can you point out what I am doing wrong?


Solution

  • After checking your code and setting, there are some suggestions for you to troubleshoot it.

    1. Make sure that your Android device is not using a cellular data network because you are using a 192.168.254.173 private IP. It can work normally under the same network segment.

    2. Make sure that the parameters are the same, and the URL of the SignalR Client should be http://192.168.254.173:5050/notification?userid=1010072.

    3. Try setting a breakpoint in OnConnectedAsync and see if you can get into this method.

      ① If yes, you can debug it. Will find the problem.
      ② If no, please following the point 4 to enbale the Cors.

    4. We can enable all Origin for testing. The middleware order is very important.

      public class Program
      {
          public static void Main(string[] args)
          {
              ...
              // allow all Origin
              builder.Services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
              {
                  builder.AllowAnyMethod()
                      .SetIsOriginAllowed(_ => true)
                      .AllowAnyHeader()
                      .AllowCredentials();
              }));
              ...
              var app = builder.Build();
      
              // Configure the HTTP request pipeline.
              if (!app.Environment.IsDevelopment())
              {
                  app.UseExceptionHandler("/Home/Error");
                  // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                  app.UseHsts();
              }
      
              app.UseHttpsRedirection();
              app.UseStaticFiles();
      
              app.UseRouting();
      
              // add this line
              app.UseCors("CorsPolicy");
      
              app.UseAuthorization();
      
              app.MapControllerRoute(
                  name: "default",
                  pattern: "{controller=Home}/{action=Index}/{id?}");
      
              app.Run();
          }
      }