Error using ClientWebSocket: The 'Connection' header value 'Upgrade,Keep-Alive' is invalid. .NET Framework 4.7.2

Marcelo Cantú 0 Reputation points
2024-06-17T23:05:28.7633333+00:00

Hi, Im using .NET Framework 4.7.2 trying to connect to a WebSocket as a client, however I keep getting the same error over and over:

System.Net.WebSockets.WebSocketException (0x80004005): The 'Connection' header value 'Upgrade,Keep-Alive' is invalid.

at System.Net.WebSockets.ClientWebSocket.ValidateResponse(HttpWebRequest request, HttpWebResponse response)

at System.Net.WebSockets.ClientWebSocket.<ConnectAsyncCore>d__21.MoveNext()"

This is my code:

  using (ClientWebSocket webSocket = new ClientWebSocket())

  {


  try

  {

      webSocket.ConnectAsync(serverUri, CancellationToken.None).Wait();

      Console.WriteLine("Connected!");

      webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None).Wait();

      Console.WriteLine("Closed!");

  }

  catch (Exception e)

  {

      Console.WriteLine($"Exception: {e.Message}");

  }
  }

It seems that the class is putting Keep.Alive in the connection header and that is invalid. I tried modifying the header but it doesnt let me. Im able to connect with Postman and other libraries so the problem is not the server.

Developer technologies .NET Other
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.