Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Http.GetJsonAsync() in Blazor Server App?

As I’m currently evaluating Blazor (Server) I made a simple POC application In VS2019 (Version 16.3.8) for ordering pizzas. I created a Blazor Server App which get’s it’s data from a Web API Core 3.0 Project, nothing fency, getting data at startup in the Index razor page is implemented as next:

enter image description here

And the service which hides the external API-call is implemented as next:

enter image description here

So I’m using the regular GetStringAsync() method on the created http client instance which returns The requested data as a json-string which is finally deserialized to the required object-type. But, unfortunately I can NOT use the GetJsonAsync() method here, as shown from the GitHub samples which can be found here:

https://github.com/software-architects/learn-blazor/tree/master/samples/RestApi

enter image description here

After searching for a while, I came through next site :

https://learn-blazor.com/architecture/rest-api

which explained me I had to use the “HttpClientJsonExtensions”, as mentioned in next fragment from the site:

enter image description here

So, after downloading the samples and having a quick look at the “RestApi.Client” project (which contains the WebAssembly hosted App), I see next referenced dependencies:

enter image description here

Which has (apparently) the extension method on the “Http” class for using GetJsonAsync() method from within the Client App.

So, my question is quit obvious, how can I have the same behavior in my Blazor Server based app, because there are no Microsoft.AspNetCore.Blazor dependencies in my Blazor Server based app, as you can see next:

enter image description here

And because my PizzaMenuService lives in the “Services” folder of my Blazor Server app and makes the call to the Rest API (as shown at the beginning of my request), it doesn’t have the extension method for executing GetJsonAsync() … How can this be achieved then on a Blazor Server based app ?

Thx for any response ! 😊

Emmanuel Nuyttens.

like image 317
Emmanuel Nuyttens Avatar asked Nov 21 '19 10:11

Emmanuel Nuyttens


People also ask

How do I call a web API from Blazor WebAssembly?

In your Visual Studio create a new app and select Blazor App Template for it. Next, on the Create a new Blazor app window select Blazor WebAssembly App Template, check below image. Your app will be created with basic Blazor Configuration and a few pages. Run the app in Visual studio and you can see it runs perfectly.


2 Answers

This is how this can work in the server-side Blazor:

Add reference to Microsoft.AspNetCore.Blazor.HttpClient package

 <PackageReference Include="Microsoft.AspNetCore.Blazor.HttpClient" Version="3.0.0-preview9.19465.2" PrivateAssets="all" />

In Startup.cs, add HttpClient to DI container:

public void ConfigureServices(IServiceCollection services)
{
 ...
    if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
    {
        services.AddSingleton<HttpClient>();
    }
  ...
}

In your "service" class, inject HttpClient via constructor:

public PizaaMenuService(HttpClient httpClient)
{
    _httpClient = httpClient;
}

Then you should be able to use the HTTP and deserialization like this:

public async Task<Menu> GetPizzaMenuAsync()
        {
            string sUrl = _ApiUrlBase + "api/pizzamenu";
            return await _httpClient.GetJsonAsync<Menu>(sUrl);
        }

Note: as you are already running the application on the server, in case your API is located on the same server that serves the application, you possibly do not need to call the API via HttpClient; instead, you could directly instantiate your business objects (the same what you now do in your API controller).

like image 170
rk72 Avatar answered Oct 13 '22 00:10

rk72


The GetJsonAsync() method is an extension method for HttpClient, but it looks like what you are really trying to achieve here is one level of abstractiobn higher - i.e. deserialization to an array of Customers. RestClient.Net can do that in Blazor without the extra step.

Here is a similar call in a Blazor page:

private List<RestCountry> countries;

protected override async Task OnInitializedAsync()
{
    countries = await new Client(new NewtonsoftSerializationAdapter(), baseUri: new Uri("https://restcountries.eu/rest/v2/")).GetAsync<List<RestCountry>>();
}

Code Reference

This code works on both the server-side and client-side rendering and avoids the need to call GetJsonAsync. This article explains how to get the sample working.

like image 26
Christian Findlay Avatar answered Oct 13 '22 00:10

Christian Findlay