Migrating .NET Core 2 to .NET Core 3: HttpContent does not contain a definition for "ReadAsAsync"

ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Migrating .NET Core 2 to .NET Core 3: HttpContent does not contain a definition for "ReadAsAsync"

Message par ForumBot »

I am following this guide [https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio](https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.0&tabs=visual-studio) to migrate to .NET Core 3.

I am getting the compilation error:

Error CS1061 'HttpContent' does not contain a definition for 'ReadAsAsync' and no accessible extension method 'ReadAsAsync' accepting a first argument of type 'HttpContent' could be found (are you missing a using directive or an assembly reference?)

The project is a class library, I have updated its csproj removing a package reference to Microsoft.AspNetCore.App and adding a framework reference instead:

` <ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

```

Any ideas why this is happening?
ForumBot
Messages : 26117
Inscription : mer. avr. 22, 2026 5:33 pm

Re: Migrating .NET Core 2 to .NET Core 3: HttpContent does not contain a definition for "ReadAsAsync"

Message par ForumBot »

`ReadAsAsync` is a .NET Standard extension that's actually shared between ASP.NET Core and ASP.NET Web Api (via a NuGet library). However, it uses JSON.NET to do the deserialization, and as of .NET Core 3.0, ASP.NET Core now uses `System.Text.Json` instead. As such, this library (and the extension it contains) is not included in the .NET Core 3.0 framework because doing so would require including the JSON.NET library in addition to `System.Text.Json`.

While you can manually add the `Microsoft.AspNet.WebApi.Client` (and `Newtonsoft.Json` along with it), you should just move on without it. It doesn't save you much anyways, as you can accomplish the same via just:

`await JsonSerializer.DeserializeAsync<MyType>(await response.Content.ReadAsStreamAsync());

```

If you like, you can add your own extension to `HttpContent` to wrap this up in a `ReadAsAsync` method:
`public static class HttpContentExtensions
{
public static async Task<T> ReadAsAsync<T>(this HttpContent content) =>
await JsonSerializer.DeserializeAsync<T>(await content.ReadAsStreamAsync());
}

```
Répondre

Revenir à « .NET & C# »