Jitin
Jitin

Reputation: 344

How to replace WebRequest with HttpClient in .NET 4.8 with the ability to change request headers each time

So I have a script that sends requests with the WebRequest class. I want to change it to use HttpClient class.

It is recommended to have a singleton HttpClient class because calling it multiple times might exhaust the socket pool. But having HttpClient as singleton would mean I couldn't change the header information of a request each time. And I want to change the headers each time.

How would I implement a singleton HttpClient class with the ability to change the request headers each time?

Upvotes: 1

Views: 4915

Answers (1)

Alberto
Alberto

Reputation: 15951

Use the HttpRequestMessage class.

Example for a POST request:

using HttpRequestMessage msg = new HttpRequestMessage();
msg.RequestUri = new Uri("...");
msg.Method = HttpMethod.Post;
msg.Headers.Add("x-my-custom-header", 123);
msg.Content = new StringContent("some string content");

await httpClient.SendAsync(msg, cancellationToken);

Upvotes: 3

Related Questions