Skip to content

Commit 162f09b

Browse files
committed
Use HttpClient factory registration.
1 parent aa9ca64 commit 162f09b

4 files changed

Lines changed: 19 additions & 6 deletions

File tree

MyApp/Components/Pages/FetchData.razor

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
@page "/fetchdata"
2-
@inject HttpClient Http
2+
@inject IHttpClientFactory HttpClientFactory
33

44
<h1 class="mb-4 text-2xl font-semibold text-gray-900 dark:text-gray-100">
55
Weather forecast
@@ -24,10 +24,16 @@ else
2424
<ExampleCode Title="Source Code" Path="/FetchData.razor" />
2525

2626
@code {
27+
private HttpClient _httpClient;
28+
29+
protected override void OnInitialized()
30+
{
31+
_httpClient = HttpClientFactory.CreateClient("Blazor");
32+
}
2733
List<WeatherForecast> forecasts = new();
2834

2935
protected override async Task OnInitializedAsync()
3036
{
31-
forecasts = await Http.GetFromJsonAsync<List<WeatherForecast>>("data/weather.json") ?? forecasts;
37+
forecasts = await _httpClient.GetFromJsonAsync<List<WeatherForecast>>("data/weather.json") ?? forecasts;
3238
}
3339
}
Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
@page "/gallery/datagrid/custom"
2-
@inject HttpClient Http
2+
@inject IHttpClientFactory HttpClientFactory
33

44
<DataGrid Items=@forecasts class="max-w-screen-md" TableStyle="TableStyle.StripedRows | TableStyle.UppercaseHeadings">
55
<Column Field="(WeatherForecast x) => x.Date" Format="dd/MM/yyyy" />
@@ -9,10 +9,16 @@
99
</DataGrid>
1010

1111
@code {
12+
private HttpClient _httpClient;
13+
14+
protected override void OnInitialized()
15+
{
16+
_httpClient = HttpClientFactory.CreateClient("Blazor");
17+
}
1218
List<WeatherForecast> forecasts = new();
1319

1420
protected override async Task OnInitializedAsync()
1521
{
16-
forecasts = await Http.GetFromJsonAsync<List<WeatherForecast>>("/data/weather.json") ?? new();
22+
forecasts = await _httpClient.GetFromJsonAsync<List<WeatherForecast>>("/data/weather.json") ?? new();
1723
}
1824
}

MyApp/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@
5151

5252
var baseUrl = builder.Configuration["ApiBaseUrl"] ??
5353
(builder.Environment.IsDevelopment() ? "https://localhost:5001" : "http://" + IPAddress.Loopback);
54-
services.AddScoped(c => new HttpClient { BaseAddress = new Uri(baseUrl) });
54+
services.AddHttpClient("Blazor", client => client.BaseAddress = new Uri(baseUrl));
5555
services.AddBlazorServerIdentityApiClient(baseUrl);
5656
services.AddLocalStorage();
5757

MyApp/appsettings.Development.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,5 +7,6 @@
77
},
88
"SmtpConfig": {
99
"Host": "localhost"
10-
}
10+
},
11+
"ApiBaseUrl": "https://localhost:5001"
1112
}

0 commit comments

Comments
 (0)