Welcome to the navigation

Tempor in amet, ut ea consequat, occaecat pariatur, eu officia nisi laborum, minim voluptate nostrud ex fugiat velit dolore veniam, proident, est reprehenderit irure aute. Sed anim culpa dolore cillum pariatur, ex qui dolor amet, consequat, esse exercitation fugiat nostrud consectetur eu in voluptate cupidatat laboris sit ut excepteur ut

Yeah, this will be replaced... But please enjoy the search!

Resolving HttpContent ReadAsAsync<T> returning null in asp.net core

The HttpContent extension ReadAsAsync<T> is very practical since it will allow you to deserialize an incoming response to a typed object. When using the HttpClient in asp.net core the method will fail to perform the deserialization unless you set the mediaType in the accept headers, in example

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

A complete example would look like this

using (HttpClient client = new HttpClient())
{
    var json = new StringContent(content: jsonString, encoding: Encoding.UTF32)
    {
        Headers =
        {
            // required for json apis
            ContentType = new MediaTypeHeaderValue(mediaType: "application/json")
        }
    };

    // required to use ReadAsAsync
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

    using (var res = await client.PostAsync(requestUri: $"{apiUrl}", content: json))
    {
        using(HttpContent content = res.Content)
        {
            var typedData = await content.ReadAsAsync();
        }
    }
}

Cheers