I am trying to test HttpClient in a small WebAssemply App (created using .NET 5).
The program.cs contains following statement to add HttpClient service:
builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
The source code of my test Razor Component is posted at the end. Following exception occurred when executing the statement: "HttpResponseMessage response = await http.GetAsync(apiUrl)". The same error occurred when using http.GetFromJsonAsync<>.
I was able to Web API to get data from same website in Blazor Server app. For some reason, I could not make it work in WebAssembly app. Any help will be appreciated.
ERROR MESSAGE
mono_wasm_start_single_stepping 2
crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: TypeError: Failed to fetch
System.Net.Http.HttpRequestException: TypeError: Failed to fetch
at System.Net.Http.BrowserHttpHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
at WebAssemblyUseWebApi.Pages.Weather.OnInitializedAsync() in C:projectsmy_tryoutWebAssemblyUseWebApiWebAssemblyUseWebApiPagesWeather.razor:line 27
at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)
=============================================================================
SOURCE CODE
page "/weather"
@inject HttpClient http
<h3>Weather Data</h3>
@if (!string.IsNullOrEmpty(errorMessage))
{
<p>@errorMessage</p>
}
else if (string.IsNullOrEmpty(data))
{
<p>Loading ...</p>
}
else
{
<p>@data</p>
}
@code {
string errorMessage = string.Empty;
public string data;
protected override async Task OnInitializedAsync()
{
string apiUrl = "https://www.metaweather.com/api/location/2471217/";
HttpResponseMessage response = await http.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
data = response.Content.ReadAsStringAsync().Result;
}
else
{
errorMessage = response.ReasonPhrase;
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…