Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set custom headers for websocket handshake in .NET 4.5

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?

like image 668
polkovnikov.ph Avatar asked Jul 02 '14 11:07

polkovnikov.ph


People also ask

Can WebSockets have headers?

Warning: The server can't send more than one Sec-Websocket-Protocol header. If the server doesn't want to use any subprotocol, it shouldn't send any Sec-WebSocket-Protocol header. Sending a blank header is incorrect.

Does .NET support WebSockets?

. NET 7 introduced Websockets over HTTP/2 support for Kestrel, the SignalR JavaScript client, and SignalR with Blazor WebAssembly. HTTP/2 WebSockets use CONNECT requests rather than GET, so your own routes and controllers may need updating.

Is a WebSocket handshake requesting a change from HTTP to WebSocket protocol?

Any network communications that use the WebSocket protocol start with an opening handshake. This handshake upgrades the connection from HTTP to the WebSocket protocol. It's an upgrade of HTTP to message-based communications.


1 Answers

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

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

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

like image 188
Marc Gravell Avatar answered Oct 05 '22 22:10

Marc Gravell