问题描述
我正在尝试使用我的新 Blazor Webassembly 应用程序调用现有的 rest API,但是当我进行调用时,我总是收到错误无法评估儿童.API 到达断点,当我单步执行它时成功返回数据,我也可以查看是否在邮递员中调用它,但是 Blazor 调用失败.我认为这可能是类不匹配的问题,但是 TeamModel 的类结构是相同的,因为它现在是共享资源.我是 Blazor 的新手,我确定我遗漏了一些东西,但可以提供一些指导或帮助.
I'm trying to call an existing rest API I have with my new Blazor Webassembly app, however when I make the call I always get the error Children could not be evaluated. The API hits the breakpoint and when I step through it returns the data successfully which I can also see if I call it in postman, however the Blazor call fails. I thought perhaps it was an issue with mismatching classes, however the class structure for TeamModel is identical as it is now a shared resource. I'm new with Blazor and I'm sure I'm missing something but could do with some direction or help.
private async Task FetchTeamData()
{
try
{
List<TeamModel> teams;
teams = await Http.GetFromJsonAsync<List<TeamModel>>("http://localhost:50663/api/team");
}
catch (Exception ex)
{
//Always blowing up with Children could not be evaluated here.
}
}
[HttpGet]
public IActionResult GetAllTeams()
{
List<TeamModel> teams = _teamRepository.GetAllTeams();
return Ok(teams);
}
好吧,我已经将范围缩小到项目读取 API 的方式有问题.我可以很好地调用其他托管 API.我不确定是因为它的 localhost 还是其他一些问题,但是没有一个 localhost API 方法会正确调用我总是从它那里得到相同的响应.
Well I've narrowed it down to being something wrong with the way the project is reading that API. I can call other hosted APIs fine. I'm not sure if its because its localhost or some other issue, but none of the localhost API methods will call properly I always get the same response from it.
推荐答案
我刚刚遇到了同样的问题,这是一个 CORS 问题.只需在您的 API 服务器的 startup.cs 中添加类似这样的内容
I just ran into the same problem, it's a CORS issue. Just add in startup.cs of your API server something like this
app.UseCors(policy =>
policy.WithOrigins("http://localhost:5000", "https://localhost:5001")
.AllowAnyMethod()
.WithHeaders(HeaderNames.ContentType));
这篇关于无法评估 Blazor Webassembly API 调用子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!