Open Closed

Cannot use SignalR in microservice solution. Timeout making http request, exception: System.Threading.Tasks.TaskCanceledException: #6856


User avatar
0
malvarado created
  • ABP Framework version: v7.4.0
  • UI Type: Angular
  • Database System: EF Core (SQL Server)
  • Tiered (for MVC) or Auth Server Separated (for Angular): Separated. Microservices
  • Exception message and full stack trace: requestId: 0HN22O3N3S1OE:00000003, previousRequestId: no previous request id, message: Error Code: RequestTimedOutError Message: Timeout making http request, exception: System.Threading.Tasks.TaskCanceledException: The request was canceled due to the configured HttpClient.Timeout of 90 seconds elapsing.
  • Steps to reproduce the issue:

We added SignalR to one of our microservices and Angular frontend using the following guide: https://docs.abp.io/en/abp/latest/SignalR-Integration

When we try to use it from our frontend, the two negotiation requests resolve fine, but then when it tries to connect we get a TimeOut Exception. When we try to debug the OnConnectedAsync method in the hub we see that it doesn't stop at a breakpoint, so I understand it doesn't even execute it. The microservice (OperacionesService) doesn't throw any errors.

This is the Hub in our microservice:

public class DemoHub: AbpHub<PlanillaDespachosAppService>
{
    private readonly IPlanillaDespachoRepository _planillaDespachoRepository;

    public DemoHub(IPlanillaDespachoRepository planillaDespachoRepository)
    {
        _planillaDespachoRepository = planillaDespachoRepository;
    }

    public async override Task OnConnectedAsync()
    {
        var x = CurrentUser.Id;
        Console.WriteLine(x);
        await base.OnConnectedAsync();
    }

    public async override Task OnDisconnectedAsync(Exception exception)
    {
        var x = CurrentUser.Id;
        Console.WriteLine(x);
        await base.OnDisconnectedAsync(exception);
    }
}

This is the OnApplicationInitialization in our WebGateway:

public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
    var app = context.GetApplicationBuilder();
    var env = context.GetEnvironment();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCorrelationId();
    app.UseCors();
    app.UseSwagger();
    app.UseSwaggerUI(options =>
    {
        options.SwaggerEndpoint("/swagger/v1/swagger.json", "Web Gateway API");
        var configuration = context.ServiceProvider.GetRequiredService<IConfiguration>();
        options.OAuthClientId(configuration["AuthServer:SwaggerClientId"]);
        options.OAuthClientSecret(configuration["AuthServer:SwaggerClientSecret"]);
    });
    app.UseAbpSerilogEnrichers();
    app.MapWhen(
        ctx => ctx.Request.Path.ToString().StartsWith("/api/abp/api-definition") ||
               ctx.Request.Path.ToString().TrimEnd('/').Equals(""),
        app2 =>
        {
            app2.UseRouting();
            app2.UseConfiguredEndpoints();
        }
    );
    app.UseWebSockets();
    app.UseOcelot().Wait();
}

The SignalR config in appsettings.json of WebGateway:

{
  "DownstreamPathTemplate": "/signalr-hubs/{everything}",
  "DownstreamScheme": "https",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 44878
    }
  ],
  "UpstreamPathTemplate": "/signalr-hubs/{everything}",
  "UpstreamHttpMethod": [
    "Put",
    "Delete",
    "Get",
    "Post"
  ]
},
{
  "DownstreamPathTemplate": "/ws",
  "UpstreamPathTemplate": "/",
  "DownstreamScheme": "ws",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 44878
    }
  ]
}

The connection methods in our frontend (Angular):

private createConnection() {
    if (!this.connection) {
      this.connection = new HubConnectionBuilder()
        .withUrl('https://localhost:44325/signalr-hubs/demo',
          {
            accessTokenFactory: () => this.userService.getAccessToken(),
            transport: HttpTransportType.ServerSentEvents
          })

        // .withUrl('/Notifications',
        //     {
        //         accessTokenFactory: () => userId,
        //         // THis will use websockets by default, if it does not work try uncommenting this line
        //         // transport: HttpTransportType.ServerSentEvents
        //     })
        .withAutomaticReconnect()
        // .configureLogging(LogLevel.Debug)
        .build();
    }
  }

  connectNotifications() {
    if (!this.userService.hasValidAccessToken()) return;
    this.createConnection();

    if (this.connection.state == HubConnectionState.Disconnected)
      this.connection
        .start()
        .catch(err => console.log('Error while starting connection to notification service: ' + err));

    this.connection.on('1q1q', console.log);

  }

  sendMessage(val: string) {

    console.log(this.connection.state);

    this.connection.send('1q1q', val)
  }

When we load the page that tries to connect to the hub we get the following logs and Network status:

WebGateway:

2024-03-12 16:03:43.651 -03:00 [INF] Request starting HTTP/2 OPTIONS https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - -
2024-03-12 16:03:43.651 -03:00 [INF] CORS policy execution successful.
2024-03-12 16:03:43.651 -03:00 [INF] Request finished HTTP/2 OPTIONS https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - - - 204 - - 0.2349ms
2024-03-12 16:03:43.663 -03:00 [INF] Request starting HTTP/2 POST https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - 0
2024-03-12 16:03:43.664 -03:00 [INF] CORS policy execution successful.
2024-03-12 16:03:43.664 -03:00 [INF] requestId: 0HN22O3N3S1OM:00000001, previousRequestId: no previous request id, message: EndpointRateLimiting is not enabled for /signalr-hubs/{everything}
2024-03-12 16:03:43.664 -03:00 [INF] requestId: 0HN22O3N3S1OM:00000001, previousRequestId: no previous request id, message: No authentication needed for /signalr-hubs/demo/negotiate
2024-03-12 16:03:43.664 -03:00 [INF] requestId: 0HN22O3N3S1OM:00000001, previousRequestId: no previous request id, message: /signalr-hubs/{everything} route does not require user to be authorized
2024-03-12 16:03:43.895 -03:00 [INF] requestId: 0HN22O3N3S1OM:00000001, previousRequestId: no previous request id, message: 200 (OK) status code, request uri: https://localhost:44878/signalr-hubs/demo/negotiate?negotiateVersion=1
2024-03-12 16:03:43.895 -03:00 [INF] Request finished HTTP/2 POST https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - 0 - 200 316 application/json 231.5712ms
2024-03-12 16:03:43.906 -03:00 [INF] Request starting HTTP/2 GET https://localhost:44325/signalr-hubs/demo?id=RnQFLvileEO8aoDcl7QboQ&access_token=eyJh...asd - -
2024-03-12 16:03:43.906 -03:00 [INF] CORS policy execution successful.
2024-03-12 16:03:43.907 -03:00 [INF] requestId: 0HN22O3N3S1OM:00000003, previousRequestId: no previous request id, message: EndpointRateLimiting is not enabled for /signalr-hubs/{everything}
2024-03-12 16:03:43.907 -03:00 [INF] requestId: 0HN22O3N3S1OM:00000003, previousRequestId: no previous request id, message: No authentication needed for /signalr-hubs/demo
2024-03-12 16:03:43.907 -03:00 [INF] requestId: 0HN22O3N3S1OM:00000003, previousRequestId: no previous request id, message: /signalr-hubs/{everything} route does not require user to be authorized
2024-03-12 16:05:13.908 -03:00 [WRN] requestId: 0HN22O3N3S1OM:00000003, previousRequestId: no previous request id, message: Error Code: RequestTimedOutError Message: Timeout making http request, exception: System.Threading.Tasks.TaskCanceledException: The request was canceled due to the configured HttpClient.Timeout of 90 seconds elapsing.
 ---> System.TimeoutException: The operation was canceled.
 ---> System.Threading.Tasks.TaskCanceledException: The operation was canceled.
 ---> System.IO.IOException: Unable to read data from the transport connection: La operación de E/S se anuló por una salida de subproceso o por una solicitud de aplicación..
 ---> System.Net.Sockets.SocketException (995): La operación de E/S se anuló por una salida de subproceso o por una solicitud de aplicación.
   --- End of inner exception stack trace ---
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.ThrowException(SocketError error, CancellationToken cancellationToken)
   at System.Net.Sockets.Socket.AwaitableSocketAsyncEventArgs.System.Threading.Tasks.Sources.IValueTaskSource<System.Int32>.GetResult(Int16 token)
   at System.Net.Security.SslStream.EnsureFullTlsFrameAsync[TIOAdapter](CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource<TResult>.GetResult(Int16 token)
   at System.Net.Security.SslStream.ReadAsyncInternal[TIOAdapter](Memory`1 buffer, CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.PoolingAsyncValueTaskMethodBuilder`1.StateMachineBox`1.System.Threading.Tasks.Sources.IValueTaskSource&lt;TResult&gt;.GetResult(Int16 token)
   at System.Net.Http.HttpConnection.FillAsync(Boolean async)
   at System.Net.Http.HttpConnection.ChunkedEncodingReadStream.CopyToAsyncCore(Stream destination, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at System.Net.Http.HttpConnection.ChunkedEncodingReadStream.CopyToAsyncCore(Stream destination, CancellationToken cancellationToken)
   at System.Net.Http.HttpConnectionResponseContent.&lt;SerializeToStreamAsync&gt;g__Impl|6_0(Stream stream, TransportContext context, CancellationToken cancellationToken)
   at System.Net.Http.HttpContent.LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer)
   at System.Net.Http.HttpClient.&lt;SendAsync&gt;g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   --- End of inner exception stack trace ---
   --- End of inner exception stack trace ---
   at System.Net.Http.HttpClient.HandleFailure(Exception e, Boolean telemetryStarted, HttpResponseMessage response, CancellationTokenSource cts, CancellationToken cancellationToken, CancellationTokenSource pendingRequestsCts)
   at System.Net.Http.HttpClient.&lt;SendAsync&gt;g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
   at Ocelot.Requester.HttpClientHttpRequester.GetResponse(HttpContext httpContext) errors found in ResponderMiddleware. Setting error response for request path:/signalr-hubs/demo, request method: GET
2024-03-12 16:05:13.908 -03:00 [INF] Request finished HTTP/2 GET https://localhost:44325/signalr-hubs/demo?id=RnQFLvileEO8aoDcl7QboQ&access_token=eyJh...asd - - - 503 0 - 90002.9186ms

OperacionesService:

2024-03-12 16:03:43.676 -03:00 [INF] Request starting HTTP/1.1 POST https://localhost:44878/signalr-hubs/demo/negotiate?negotiateVersion=1 - 0
2024-03-12 16:03:43.889 -03:00 [INF] Executing endpoint '/signalr-hubs/demo/negotiate'
2024-03-12 16:03:43.894 -03:00 [INF] Executed endpoint '/signalr-hubs/demo/negotiate'
2024-03-12 16:03:43.895 -03:00 [INF] Request finished HTTP/1.1 POST https://localhost:44878/signalr-hubs/demo/negotiate?negotiateVersion=1 - 0 - 200 316 application/json 218.4628ms
2024-03-12 16:03:43.908 -03:00 [INF] Request starting HTTP/1.1 GET https://localhost:44878/signalr-hubs/demo?id=RnQFLvileEO8aoDcl7QboQ&access_token=eyJhb...asd - 0
2024-03-12 16:03:43.910 -03:00 [INF] Executing endpoint '/signalr-hubs/demo'
2024-03-12 16:05:13.918 -03:00 [INF] Executed endpoint '/signalr-hubs/demo'
2024-03-12 16:05:13.920 -03:00 [INF] Request finished HTTP/1.1 GET https://localhost:44878/signalr-hubs/demo?id=RnQFLvileEO8aoDcl7QboQ&access_token=eyJhb...asd - 0 - 200 - text/event-stream 90013.2758ms


13 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    transport: HttpTransportType.ServerSentEvents

    Can you try using websocket instead of ServerSentEvents?

  • User Avatar
    0
    malvarado created

    Hello liangshiwei,

    I just tried that. Now I'm not getting the TimeOut error, but it seems it's still not connecting correctly. These are the logs:

    WebGateway (You can see a UnableToFindDownstreamRouteError error):

    2024-03-13 08:57:47.440 -03:00 [INF] Request starting HTTP/2 OPTIONS https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - -
    2024-03-13 08:57:47.440 -03:00 [INF] CORS policy execution successful.
    2024-03-13 08:57:47.440 -03:00 [INF] Request finished HTTP/2 OPTIONS https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - - - 204 - - 0.2458ms
    2024-03-13 08:57:47.451 -03:00 [INF] Request starting HTTP/2 POST https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - 0
    2024-03-13 08:57:47.451 -03:00 [INF] CORS policy execution successful.
    2024-03-13 08:57:47.452 -03:00 [INF] requestId: 0HN22O3N3S1OQ:00000001, previousRequestId: no previous request id, message: EndpointRateLimiting is not enabled for /signalr-hubs/{everything}
    2024-03-13 08:57:47.452 -03:00 [INF] requestId: 0HN22O3N3S1OQ:00000001, previousRequestId: no previous request id, message: No authentication needed for /signalr-hubs/demo/negotiate
    2024-03-13 08:57:47.452 -03:00 [INF] requestId: 0HN22O3N3S1OQ:00000001, previousRequestId: no previous request id, message: /signalr-hubs/{everything} route does not require user to be authorized
    2024-03-13 08:57:47.465 -03:00 [INF] requestId: 0HN22O3N3S1OQ:00000001, previousRequestId: no previous request id, message: 200 (OK) status code, request uri: https://localhost:44878/signalr-hubs/demo/negotiate?negotiateVersion=1
    2024-03-13 08:57:47.466 -03:00 [INF] Request finished HTTP/2 POST https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - 0 - 200 316 application/json 14.6363ms
    2024-03-13 08:57:47.478 -03:00 [INF] Request starting HTTP/2 CONNECT https://localhost:44325/signalr-hubs/demo?id=-BoVMzEFfiK1Z_aHpGzQGw&access_token=eyJh...asd - -
    2024-03-13 08:57:47.478 -03:00 [INF] CORS policy execution successful.
    2024-03-13 08:57:47.478 -03:00 [WRN] requestId: 0HN22O3N3S1OQ:00000003, previousRequestId: no previous request id, message: DownstreamRouteFinderMiddleware setting pipeline errors. IDownstreamRouteFinder returned Error Code: UnableToFindDownstreamRouteError Message: Failed to match Route configuration for upstream path: /signalr-hubs/demo, verb: CONNECT.
    2024-03-13 08:57:47.478 -03:00 [INF] Request finished HTTP/2 CONNECT https://localhost:44325/signalr-hubs/demo?id=-BoVMzEFfiK1Z_aHpGzQGw&access_token=eyJh...asd - - - 200 - - 0.5002ms
    2024-03-13 08:57:47.478 -03:00 [INF] Connection id "0HN22O3N3S1OQ", Request id "0HN22O3N3S1OQ:00000003": the application completed without reading the entire request body.
    
    

    OperacionesService:

    2024-03-13 08:57:47.462 -03:00 [INF] Request starting HTTP/1.1 POST https://localhost:44878/signalr-hubs/demo/negotiate?negotiateVersion=1 - 0
    2024-03-13 08:57:47.464 -03:00 [INF] Executing endpoint '/signalr-hubs/demo/negotiate'
    2024-03-13 08:57:47.465 -03:00 [INF] Executed endpoint '/signalr-hubs/demo/negotiate'
    2024-03-13 08:57:47.465 -03:00 [INF] Request finished HTTP/1.1 POST https://localhost:44878/signalr-hubs/demo/negotiate?negotiateVersion=1 - 0 - 200 316 application/json 3.4574ms
    

    The request appears to return a 200 code, but it still doesn't get to the hub methods:

    Also when we try to send a message we still get the following error (we were getting the same error before the change you suggested also):

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    You can try updating your Ocelot config

    {
        
        "DownstreamPathTemplate": "/signalr-hubs/{everything}",
        "DownstreamScheme": "ws", // or wss
        "DownstreamHostAndPorts": [
            {
            "Host": "localhost",
            "Port": 44878
            }
        ],
        "UpstreamPathTemplate": "/signalr-hubs/{everything}"
    }
    
  • User Avatar
    0
    malvarado created

    I'm still getting errors with signalr. I tried updating the Ocelot config as you mentioned and it still doesn't work.

    I tried different configurations and it throws different errors. With this current configuration, both handshakes return 200 codes. Then the WS request returns a 200 code but appears to throw and "Unrecognized frame upcode: 6" error, and we get a new Exception on the WebGateway log:

    Current WebGateway config:

    {
      "DownstreamPathTemplate": "/signalr-hubs/{everything}",
      "DownstreamScheme": "wss",
      "DownstreamHostAndPorts": [
    	{
    	  "Host": "localhost",
    	  "Port": 44878
    	}
      ],
      "UpstreamPathTemplate": "/signalr-hubs/{everything}"
    },
    {
      "DownstreamPathTemplate": "/ws",
      "UpstreamPathTemplate": "/",
      "DownstreamScheme": "wss",
      "DownstreamHostAndPorts": [
    	{
    	  "Host": "localhost",
    	  "Port": 44878
    	}
      ]
    }
    

    WebGateway logs:

    2024-03-14 13:34:20.456 -03:00 [INF] Request starting HTTP/2 OPTIONS https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - -
    2024-03-14 13:34:20.457 -03:00 [INF] CORS policy execution successful.
    2024-03-14 13:34:20.457 -03:00 [INF] Request finished HTTP/2 OPTIONS https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - - - 204 - - 0.4313ms
    2024-03-14 13:34:20.470 -03:00 [INF] Request starting HTTP/2 POST https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - 0
    2024-03-14 13:34:20.471 -03:00 [INF] CORS policy execution successful.
    2024-03-14 13:34:20.471 -03:00 [INF] requestId: 0HN248IBU7TIA:00000001, previousRequestId: no previous request id, message: EndpointRateLimiting is not enabled for /signalr-hubs/{everything}
    2024-03-14 13:34:20.471 -03:00 [INF] requestId: 0HN248IBU7TIA:00000001, previousRequestId: no previous request id, message: No authentication needed for /signalr-hubs/demo/negotiate
    2024-03-14 13:34:20.471 -03:00 [INF] requestId: 0HN248IBU7TIA:00000001, previousRequestId: no previous request id, message: /signalr-hubs/{everything} route does not require user to be authorized
    2024-03-14 13:34:20.485 -03:00 [INF] requestId: 0HN248IBU7TIA:00000001, previousRequestId: no previous request id, message: 200 (OK) status code, request uri: wss://localhost:44878/signalr-hubs/demo/negotiate?negotiateVersion=1
    2024-03-14 13:34:20.485 -03:00 [INF] Request finished HTTP/2 POST https://localhost:44325/signalr-hubs/demo/negotiate?negotiateVersion=1 - 0 - 200 316 application/json 14.7364ms
    2024-03-14 13:34:20.497 -03:00 [INF] Request starting HTTP/2 CONNECT https://localhost:44325/signalr-hubs/demo?id=O_QfCDfM1fl8YqKTWpheSg&access_token=eyJh...asd - -
    2024-03-14 13:34:20.497 -03:00 [INF] CORS policy execution successful.
    2024-03-14 13:34:20.524 -03:00 [ERR] requestId: 0HN248IBU7TIA:00000003, previousRequestId: no previous request id, message: Exception caught in global error handler, exception message: The WebSocket is in an invalid state ('Aborted') for this operation. Valid states are: 'Open, CloseReceived', exception stack:    at System.Net.WebSockets.WebSocketValidate.ThrowIfInvalidState(WebSocketState currentState, Boolean isDisposed, WebSocketState[] validStates)
       at System.Net.WebSockets.ManagedWebSocket.CloseOutputAsyncCore(WebSocketCloseStatus closeStatus, String statusDescription, CancellationToken cancellationToken)
       at Ocelot.WebSockets.Middleware.WebSocketsProxyMiddleware.PumpWebSocket(WebSocket source, WebSocket destination, Int32 bufferSize, CancellationToken cancellationToken)
       at Ocelot.WebSockets.Middleware.WebSocketsProxyMiddleware.Proxy(HttpContext context, String serverEndpoint)
       at Ocelot.WebSockets.Middleware.WebSocketsProxyMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.DownstreamUrlCreator.Middleware.DownstreamUrlCreatorMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.LoadBalancer.Middleware.LoadBalancingMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.Request.Middleware.DownstreamRequestInitialiserMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.Multiplexer.MultiplexingMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.DownstreamRouteFinder.Middleware.DownstreamRouteFinderMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.Errors.Middleware.ExceptionHandlerMiddleware.Invoke(HttpContext httpContext) RequestId: 0HN248IBU7TIA:00000003
    System.Net.WebSockets.WebSocketException (0x80004005): The WebSocket is in an invalid state ('Aborted') for this operation. Valid states are: 'Open, CloseReceived'
       at System.Net.WebSockets.WebSocketValidate.ThrowIfInvalidState(WebSocketState currentState, Boolean isDisposed, WebSocketState[] validStates)
       at System.Net.WebSockets.ManagedWebSocket.CloseOutputAsyncCore(WebSocketCloseStatus closeStatus, String statusDescription, CancellationToken cancellationToken)
       at Ocelot.WebSockets.Middleware.WebSocketsProxyMiddleware.PumpWebSocket(WebSocket source, WebSocket destination, Int32 bufferSize, CancellationToken cancellationToken)
       at Ocelot.WebSockets.Middleware.WebSocketsProxyMiddleware.Proxy(HttpContext context, String serverEndpoint)
       at Ocelot.WebSockets.Middleware.WebSocketsProxyMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.DownstreamUrlCreator.Middleware.DownstreamUrlCreatorMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.LoadBalancer.Middleware.LoadBalancingMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.Request.Middleware.DownstreamRequestInitialiserMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.Multiplexer.MultiplexingMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.DownstreamRouteFinder.Middleware.DownstreamRouteFinderMiddleware.Invoke(HttpContext httpContext)
       at Ocelot.Errors.Middleware.ExceptionHandlerMiddleware.Invoke(HttpContext httpContext)
    2024-03-14 13:34:20.525 -03:00 [INF] Request finished HTTP/2 CONNECT https://localhost:44325/signalr-hubs/demo?id=O_QfCDfM1fl8YqKTWpheSg&access_token=eyJh...asd - - - 200 - - 28.1154ms
    

    The WS request returns a 200 code, but in the messages tab it shows an error:

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    This may be a problem with Ocelot, I'm not sure.

    https://github.com/ThreeMammals/Ocelot/issues/930

    Could you share a simple project via email that can reproduce the problem with me? I will check it. thanks shiwei.liang@volosoft.com

  • User Avatar
    0
    malvarado created

    Hi,

    I just sent you an example project via email. Please, let me know if you need anything else to test the problem.

    Thanks!

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    1. Update route config:
    {
          "DownstreamPathTemplate": "/signalr-hubs/{everything}",
          "DownstreamScheme": "wss",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 44361
            }
          ],
          "UpstreamPathTemplate": "/signalr-hubs/{everything}"
        },
        {
          "DownstreamPathTemplate": "/ws",
          "UpstreamPathTemplate": "/",
          "DownstreamScheme": "wss",
          "DownstreamHostAndPorts": [
            {
              "Host": "localhost",
              "Port": 44361
            }
          ]
        }
    
    1. Add app.UseWebSockets(); to TransitWebGatewayModule
    app.UseWebSockets();
    app.UseOcelot().Wait();
    
    1. Update ServiciodemoService
    private createConnection() {
    if (!this.connection) {
      this.connection = new HubConnectionBuilder()
        .withUrl('https://localhost:44325/signalr-hubs/demo',
          {
            accessTokenFactory: () => this.userService.getAccessToken(),
            transport: HttpTransportType.WebSockets
          })
    
        // .withUrl('/Notifications',
        //     {
        //         accessTokenFactory: () => userId,
        //         // THis will use websockets by default, if it does not work try uncommenting this line
        //         // transport: HttpTransportType.ServerSentEvents
        //     })
        .withAutomaticReconnect()
        // .configureLogging(LogLevel.Debug)
        .build();
    
        this.connection.start();
    }
    }
    

  • User Avatar
    0
    malvarado created

    Hi,

    Can you upload the full solution to the same Google Drive I uploaded it?

    I implemented the fixes and I'm still getting the same errors:

    • Handshakes work fine
    • Requests returns 200 code, but I'm still getting the errors:
      • On frontend: WebSocket connection to 'wss://localhost:44325/signalr-hubs/demo?id=G-hyAmzj1-GUAN6EYnrTyw' failed: Unrecognized frame opcode: 6 WebSocket closed with status code: 1006 (no reason given).
      • On WebGateway log:
    requestId: 0HN28RBEI53CU:00000003, previousRequestId: no previous request id, message: Exception caught in global error handler, exception message: The WebSocket is in an invalid state ('Aborted') for this operation. Valid states are: 'Open, CloseReceived', exception stack:    at System.Net.WebSockets.WebSocketValidate.ThrowIfInvalidState(WebSocketState currentState, Boolean isDisposed, WebSocketState[] validStates)
    

    Thanks!

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Ok, shared

  • User Avatar
    0
    malvarado created

    Hello,

    We are still experiencing the same errors.

    Could this be an issue related to some configuration on our machines related to WebSockets? Or maybe the Locale/Region the frontend and backend are configured? (maybe the Signalr library expects or uses english, and the locales in our machines are in spanish)

    Thanks!

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    It looks like SignalR is working, but the connect is closed abnormally.

    You can check those: https://stackoverflow.com/questions/53944572/signalr-core-error-websocket-closed-with-status-code-1006 https://stackoverflow.com/questions/19304157/getting-the-reason-why-websockets-closed-with-close-code-1006

  • User Avatar
    0
    malvarado created

    Hi,

    I made some more tests, and I found out that if I run the WebGateway with IIS Express from Visual Studio, Signalr works fine.

    I only get the errors when I run the csproj direclty, either from Visual Studio or with Tye.

    Why could this be? Is there a way to configure the csproj, Program.cs, or tye so it has the same behavior as when running it with IIS?

    Thanks.

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    Maybe you can check this: https://github.com/dotnet/aspnetcore/issues/41675 They explain how to view more detailed logs to check the cause of the error

Made with ❤️ on ABP v8.2.0-preview Updated on March 25, 2024, 15:11