问题描述
我正在尝试在小型WebAssemply应用程序(使用.NET 5创建)中测试HttpClient.program.cs包含以下语句以添加HttpClient服务:
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) });
我的测试剃刀组件的源代码发布在最后.执行该语句时发生以下异常:"HttpResponseMessage response = await http.GetAsync(apiUrl)".使用http.GetFromJsonAsync<>时,发生了相同的错误.我能够使用Web API从Blazor Server应用程序中的同一网站获取数据.由于某种原因,我无法使其在WebAssembly应用程序中工作.任何帮助将不胜感激.
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.
源代码
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;
}
}
}
推荐答案
该站点似乎不允许浏览器发出请求.
That site does not seem to allow requests from a Browser.
响应中没有CORS标头(access-control-allow-origin = ...).
There is no CORS header (access-control-allow-origin=...) in the response.
您可以使用Blazor Serverside或将API服务器添加到WebAssembly项目.在尝试重新发明轮子之前,请先查看一下"Wasm托管"模板.
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.
这篇关于如何解决WebAssembly App中与HttpClient相关的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!