Search code examples
c#asp.net-corehttpresponse

Has HttpContent.ReadAsAsync<T> method been superceded in .NET Core?


The following refers to a .NET Core application with dependencies as follows...

Microsoft.NETCore.App
Microsoft.AspNet.WepApi.Client (5.2.7)

At Microsoft.com is the document Call a Web API From a .NET Client (C#) from 2017 November.

Link... https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Within the document is this client side invocation of HTTP GET.

    static HttpClient client = new HttpClient();
    static async Task<Product> GetProductAsync(string path)
    {
        Product product = null;
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.IsSuccessStatusCode)
        {
            product = await response.Content.ReadAsAsync<Product>();
        }
        return product;
    }

The value response.Content refers to an HttpContent object. As of 2020 July HttpContent has no instance method with the signature ReadAsAsync<T>(), at least according to the following document. However, this instance method works.

Reference link to where there is no instance method with the signature ReadAsAsync<T>()... https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpcontent?view=netcore-3.1

There is a static method HttpContentExtensions.ReadAsAsync<T>(myContent) where myContent refers to an HttpContent object. This static method also works.

Reference link... https://learn.microsoft.com/en-us/previous-versions/aspnet/hh834253(v=vs.118)

For example one documented signature has the...

static icon followed by ReadAsAsync<T>(HttpContent)

and a description that says it will return Task<T>. This static method is probably the behind the scenes implementation of the instance method.

However there is information at the top of the static method webpage that indicates... "We're no longer updating this content regularly. Check the Microsoft Product Lifecycle for information about how this product, service, technology, or API is supported."

Has HttpContent.ReadAsAsync<T>() of both forms, instance and static, been superceded in .NET Core 3.1?


Solution

  • I can't tell from the code if it ever was an instance method but it probably was.

    The links you included alternate between .net 4.x and .net core, it's not clear if you are aware of this. Labelling them with dates suggests a linear progression but we have a fork in the road.

    And that is all, it was 'demoted' to residing in an additional package because it will be used less. In .net core we now have similar extensionmethods acting on HttpClient directly.


    In order to use this with .net core 3.x you may have to add the System.Net.Http.Json nuget package. The extensions only work with System.Text.Json, for Newtonsoft you will have to use the traditional code patterns.