System.Net.Http.HttpClient vs Windows.Web.Http.HttpClient – What are the main differences?

Windows.Web.Http is a WinRT API available in all the WinRT programming languages supported: C#, VB, C++/CX and JavaScript. This enables the option to write the same code in the language of your choice. System.Net.Http is a .NET API, and it is only available for C# and VB developers. Windows.Web.Http advantages WinRT APIs are written in … Read more

Httpclient This instance has already started one or more requests. Properties can only be modified before sending the first request

HttpClient.DefaultRequestHeaders (and BaseAddress) should only be set once, before you make any requests. HttpClient is only safe to use as a singleton if you don’t modify it once it’s in use. Rather than setting DefaultRequestHeaders, set the headers on each HttpRequestMessage you are sending. var request = new HttpRequestMessage(HttpMethod.Post, url); request.Headers.Accept.Clear(); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(“application/json”)); request.Headers.Authorization = … Read more

Dependency injection: HttpClient or HttpClientFactory?

Summary HttpClient can only be injected inside Typed clients for other usages, you need IHttpClientFactory In both scenarios, the lifetime of HttpClientMessageHandler is managed by the framework, so you are not worried about (incorrectly) disposing the HttpClients. Examples In order to directly inject HttpClient, you need to register a specific Typed service that will receive … Read more

C# Add Accept header to HttpClient

There is no difference. DefaultRequestHeaders.Accept is a collection of string type, where you can add your header to accept using the new instance of MediaTypeWithQualityHeaderValue. client.DefaultRequestHeaders is a dictionary that accepts key for and value for the request header and matches the results according to them. DefaultRequestHeaders has overloads. The only thing that differs between … Read more

Use HttpClientFactory from .NET 4.6.2

All of the Microsoft.Extensions.* packages target .NET Standard 2.0. That means that you can use Dependency Injection, Configuration, Logging and HttpClientFactory if you add the appropriate package to your application. You need to add Microsoft.Extensions.Http to use HttpClientFactory and Microsoft.Extensions.Http.Polly if you want to use it with Polly To configure HttpClientFactory you’ll have to add … Read more

Post byte array to Web API server using HttpClient

WebAPI v2.1 and beyond supports BSON (Binary JSON) out of the box, and even has a MediaTypeFormatter included for it. This means you can post your entire message in binary format. If you want to use it, you’ll need to set it in WebApiConfig: public static class WebApiConfig { public static void Register(HttpConfiguration config) { … Read more