Do HttpClient and HttpClientHandler have to be disposed between requests?

System.Net.Http.HttpClient and System.Net.Http.HttpClientHandler in .NET Framework 4.5 implement IDisposable (via System.Net.Http.HttpMessageInvoker). The using statement documentation says: As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. This answer uses this pattern: var baseAddress = new Uri(“http://example.com”); var cookieContainer = new CookieContainer(); using (var handler = new … Read more

Why is HttpClient BaseAddress not working?

Consider the following code, where the BaseAddress defines a partial URI path. using (var handler = new HttpClientHandler()) using (var client = new HttpClient(handler)) { client.BaseAddress = new Uri(“http://something.com/api”); var response = await client.GetAsync(“/resource/7”); } I expect this to perform a GET request to http://something.com/api/resource/7. But it doesn’t. After some searching, I find this question … Read more

How do you set the Content-Type header for an HttpClient request?

I’m trying to set the Content-Type header of an HttpClient object as required by an API I am calling. I tried setting the Content-Type like below: using (var httpClient = new HttpClient()) { httpClient.BaseAddress = new Uri(“http://example.com/”); httpClient.DefaultRequestHeaders.Add(“Accept”, “application/json”); httpClient.DefaultRequestHeaders.Add(“Content-Type”, “application/json”); // … } It allows me to add the Accept header but when I … Read more