C#C
C#3y ago
30 replies
_vegabyte_

❔ Call API From Web API on Blazor Server

Hello respected community members,
I am new to Blazor Server and I am currently trying to fetch data from a .NET Core Web API to populate a data table. I am struggling with getting the data and then displaying it in my Blazor component.
I have an HttpClient service and I'm sending a GET request to my API endpoint. The API is working correctly.
However, I am having trouble deserializing this JSON response and showing it in a table in my Blazor component.
Here is the pertinent part of my code:

private readonly string _apiUrl = "http://localhost:5278/";

    private GetAllApprovedProspectResult? prospects;

     protected override async Task OnInitializedAsync()
         {
             await RefreshList();
         }
     
         private async Task RefreshList()
         {
             try
             {
                 var request = new HttpRequestMessage(HttpMethod.Get,
                     _apiUrl + "api/Prospecting/GetAllApprovedProspect");

                 var client = ClientFactory.CreateClient();

                 var response = await client.SendAsync(request);

                 if (response.IsSuccessStatusCode)
                 {
                     using var responseStream = await response.Content.ReadAsStreamAsync();
                     prospects = await JsonSerializer.DeserializeAsync
                         <GetAllApprovedProspectResult>(responseStream);
                 }
                 else
                 {
                     getProspectError = true;
                 }

                 shouldRender = true;
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex.Message);
             }
         }
Was this page helpful?