Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

blazor - How to Resove Error Related to HttpClient in WebAssembly App

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That site does not seem to allow requests from a Browser.

There is no CORS header (access-control-allow-origin=...) in the response.

You can use either Blazor Serverside or add an API server to your WebAssembly project. Do have a look at the Wasm Hosted template before you try to reinvent the wheel.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...