Search code examples
c#.netblazordotnet-httpclient

HttpClient has no definition for GetJsonAsync


I'm currently tapping into Blazor, and want to move my code so it's more readable and reusable. In my razor component, the Method works flawlessly - in a Class, it doesn't.

In my component, I can simply use this:

response = await Http.GetJsonAsync<T>(Uri);

In my Class, Visual Studio complains that System.Net.Http's HttpClient contains no definition for GetJsonAsync - but I'm getting a typed response, so I want to deserialize it properly.


Solution

  • Great question. And I'm assuming Darrell's answer (and the others) was 100% correct as of version 3.0.0 (Blazor WebAssembly preview).

    However, as for version 3.1.301 I think the package location has changed.

    Currently, the namespace is: System.Net.Http.Json

    That will give you access to: HttpClientJsonExtensions

    A. If you want to put that code into a separate class within your Blazor WebAssembly project, all you need is to put this at the top of your class file:

    using System.Net.Http; // for HttpClient
    using System.Net.Http.Json; // for HttpClientJsonExtensions
    

    B. If you want to put that class into a separate project (.NET Core library) then you need to add the NuGet package also:

    NuGet package: System.Net.Http.Json

    Then you can use it in your class like in the example below. Obviously these extension methods are doing serialization, but what's interesting is that the package doesn't depend on Newtonsoft.Json because it uses the new System.Text.Json instead.

    using System;
    using System.Net.Http;
    using System.Net.Http.Json;
    using System.Threading.Tasks;
    
    namespace MyClassLibrary
    {
        public class MyClass
        {
            public async Task MyMethod()
            {
                string baseAddress = "http://localhost:57012/";
                var httpClient = new HttpClient() { BaseAddress = new Uri(baseAddress) };
                var myPocos = await httpClient.GetFromJsonAsync<MyPoco[]>("api/mypocos");
    
                foreach (var myPoco in myPocos)
                    Console.WriteLine($"Id: {myPoco.Id}, Name: {myPoco.Name}");
            }
        }
    
        public class MyPoco
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
    }