diff --git a/Blazor3State/Pages/FetchData.razor b/Blazor3State/Pages/FetchData.razor index 2cc6efe..1c64f95 100644 --- a/Blazor3State/Pages/FetchData.razor +++ b/Blazor3State/Pages/FetchData.razor @@ -1,7 +1,9 @@ @page "/fetchdata" @using Blazor3State.Data -@inject WeatherForecastService ForecastService +@using System.IO + +@inject IHttpClientFactory httpClientFactory

Showing states in blazor

@@ -14,7 +16,7 @@
- Alternate text + Alternate text

An error has occurred. Click new image to try again !

@@ -25,21 +27,58 @@ @code { Random random = new Random(); LoadingContainerState state; + string imageData; protected override async Task OnInitializedAsync() { await LoadImage(); } + //async Task LoadImage() + //{ + // state = LoadingContainerState.Loading; + // await Task.Delay(2000); + // if (random.Next(3) == 2) + // { + // state = LoadingContainerState.Error; + // } + // else state = LoadingContainerState.Loaded; + + //} + async Task LoadImage() { state = LoadingContainerState.Loading; await Task.Delay(2000); - if (random.Next(3) == 2) - { - state = LoadingContainerState.Error; - } - else state = LoadingContainerState.Loaded; + var request = new HttpRequestMessage(HttpMethod.Get, "https://loremflickr.com/400/500"); + + var client = httpClientFactory.CreateClient(); + + var response = await client.SendAsync(request); + + if (response.IsSuccessStatusCode) + { + using var responseStream = await response.Content.ReadAsStreamAsync(); + var header = response.Content.Headers.FirstOrDefault(x => x.Key == "Content-Type"); + string imageType = header.Value.First(); + + string encodedImage; + using (MemoryStream m = new MemoryStream()) + { + responseStream.CopyTo(m); + byte[] imageBytes = m.ToArray(); + encodedImage = Convert.ToBase64String(imageBytes); + } + + imageData = $"data:{imageType};base64,{encodedImage}"; + state = LoadingContainerState.Loaded; + + } + else + state = LoadingContainerState.Error; } + + + } diff --git a/Blazor3State/Startup.cs b/Blazor3State/Startup.cs index ad5c454..f317046 100644 --- a/Blazor3State/Startup.cs +++ b/Blazor3State/Startup.cs @@ -29,6 +29,7 @@ namespace Blazor3State services.AddRazorPages(); services.AddServerSideBlazor(); services.AddSingleton(); + services.AddHttpClient(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/Blazor3State/wwwroot/css/site.css b/Blazor3State/wwwroot/css/site.css index cf7efff..c97feda 100644 --- a/Blazor3State/wwwroot/css/site.css +++ b/Blazor3State/wwwroot/css/site.css @@ -187,8 +187,8 @@ app { justify-content: center; align-items: center; background: #aaa; - height: 300px; - width: 200px; + height: 500px; + width: 400px; } .lds-default {