C# – Set custom headers for websocket handshake in .NET 4.5

chttpnetwebsocket

I'm trying to set a WebSocket connection of C# client with third-party server. When I connect with JS client to the same server, it establishes connection and everything goes fine. C# client connects to the server, but for some unknown reason server responds with 500 code. Debugging with WireShark has shown that HTTP handshake phase of WebSocket connection differs between client implementation in a set of headers. I would like to tweak the headers default System.Net.WebSockets.ClientWebSocket class sends to the server to check that the issue is there. Though, I couldn't find a way to do that.

How do I instruct ClientWebSocket of some other class in that namespace to send additional given headers in handshake phase?

Best Answer

It looks like this is exposed by ClientWebSocketOptions.SetRequestHeader, so:

obj.Options.SetRequestHeader("foo", "bar");

should work. This also provides access to AddSubProtocol(...).

Related Topic