W Almeida
W Almeida

Reputation: 27

How can I send a raw HTTP request in C#?

I am writing a .NET 5 application which sends requests over a TLS connection to some endpoint.

I tried to use HTTPClient, but it didnt work since i need to construct a HTTPRequestMessage before call the Send method.

HttpClient client = new HttpClient();
var response = await client.SendAsync(requestMessage);

var responseContent = await response.Content.ReadAsStringAsync();

I need to send the bytes of pre-serialized request above without converting it to an HTTP object.

POST /app/test HTTP/1.1
Content-type: application/json
Content-Length: 23

{"msg": "test message"}

Upvotes: 0

Views: 1271

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 456322

I need to send the bytes of pre-serialized request above without converting it to an HTTP object.

This is extremely unusual. HttpClient can't be used for this, unless you know of a parser for HttpRequestMessage. There may be a library out there that does that, but I don't know of one.

To send a byte array, you'd have to use a lower-level connection like Socket or TcpClient. And you'll need to do your own TLS negotiation - SslStream may help there.

Upvotes: 3

Related Questions