skip to Main Content

I have the following relevant code on my ASP.NET server:

// TrackingHub.cs
public class TrackingHub : Hub
{
    public async Task SendLocationData(LocationData locationData)
    {
        await Clients.Others.SendAsync("ReceiveLocationData", locationData);
        Console.WriteLine($"{locationData.Latitude}, {locationData.Longitude}");
    }
}

// Program.cs
builder.Services.AddSignalR()
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(builder =>
    {
        builder.WithOrigins("http://localhost:3000").AllowAnyHeader().AllowAnyMethod().AllowCredentials();
    });
});

//app.UseHttpsRedirection();
app.UseCors();
app.MapHub<TrackingHub>("/tracking");

Now on my .NET console app, I have the following relevant code. It works well and I receive the location data from it on my asp.net server:

HubConnection? hubConnection = new HubConnectionBuilder()
     .WithUrl("http://localhost:5191/tracking")
     .Build();

// stuff...
if (hubConnection != null)
{
    await hubConnection.SendAsync("SendLocationData", locationData);
}

And finally, this is the code I have on my react (NextJS) app:

const page = () => {
    const connection = new HubConnectionBuilder()
        .withUrl('http://localhost:5191/tracking')
        .withAutomaticReconnect()
        .build()

    connection.on('ReceiveLocationData', (locationData) => {
        console.log(locationData)
    });

    useEffect(() => {
        const startConnection = async () => {
            try {
                await connection.start()
            }
            catch (error) {
                console.log("Failed to start connection: ", error)
            }
        }

        startConnection()
    }, []);

    return (
        <Map />
    )
}

The connection, however, is not working with the React app. Note that other connections from the react app to the server work just fine (like regular GET or POST methods). I also checked the transport type being used by the working console app to see if websocket protocol is even functional or supported, and it was indeed using Websockets, which I checked using [https://stackoverflow.com/questions/49473648/determine-transport-method-in-signalr-core].

Here is an image of what I am getting on the console:

Errors from SignalR connection in react app

2

Answers


  1. Chosen as BEST ANSWER

    @JasonPan answer partially worked to mitigate the issue (which was adding skipNegotiation: true, transport: signalR.HttpTransportType.WebSockets to the client side connection).

    However, it didn't address the real issue as the connection should work regardless even without those options. I asked on the aspnetcore github repo and they suggested that it might be beacuse of adblock https://github.com/dotnet/aspnetcore/issues/49918. So, I disabled adblock and everything worked properly without having to add skipNegotiation: true, transport: signalR.HttpTransportType.WebSockets.

    I guess though, if the user does have adblock and ignores the warning that adblock in incompatible with the app, then that would be a nice workaround to use without having them disable adblock (although they have to have support for websockets, which is pretty much all users nowadays).


  2. Add the proxy setting like below in your next.config.js file.

    /** @type {import('next').NextConfig} */
    
    const nextConfig = [
        {
          context: [
            "/tracking"
         ],
          target: "http://localhost:5191", 
          changeOrigin: true,  
          logLevel: "debug",
          rejectUnauthorzied: true, 
          secure: false,            
          strictSSL: true,          
          withCredentials: true,
          // It is important
          ws: true
        }
      ]
    
    module.exports = nextConfig
    

    Then in my side, I also change the code like below.

    const connection = new signalR.HubConnectionBuilder()
      .withUrl("http://localhost:55377/mainhub", {
        skipNegotiation: true,
        transport: signalR.HttpTransportType.WebSockets
      })
      // we can enable client logging to check more details
      .configureLogging(signalR.LogLevel.Debug).build()
    

    Test Result

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search