如何在 blazor wabassembly 应用程序中查找错误(很难找到错误)

how to find the error in blazor wabassembly app(very difficult to find the error)

很难在 webassembly(客户端)blazor 中找到错误

我在客户端调用服务器端(blazor 服务器应用程序)webapi((blazor webassembly 应用程序))

首先我创建一个 blazor 服务器应用程序项目,然后使用内置的 webapi 框架进行 crud 操作

当我在客户端调用 webapi 时,很难找到错误

然后我创建一个 blazor webassembly 项目,然后将其添加到 pages 文件夹内的 razor page 下面

DisplayEmployeeData.razor

@page "/DisplayEmployeeData"
@using CrudBlazorServerApp.Data
@using System.Net.Http
@inject HttpClient Http

<h3>DisplayEmployeeData</h3>

@if (empList == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class='table'>
        <thead>
            <tr>
                <th>empid</th>
                <th>username</th>
                <th>empaddress</th>
                <th>password</th>
                <th>country</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var emp in empList)
            {
            <tr>
                <td>@emp.empid</td>
                <td>@emp.username</td>
                <td>@emp.empaddress</td>
                <td>@emp.password</td>
                <td>@emp.country</td>

            </tr>
            }
        </tbody>
    </table>
}

@code {
    Emp[] empList;
    protected override async Task OnInitializedAsync() =>
        empList = await Http.GetJsonAsync<Emp[]>("api/emps/"); //**here I put the debugger but emplist give the null**
}

什么类型的错误?

我的webapi路径不对?

查看我的控制台日志很难找到错误?

错误是关于 < 不是 Json 响应的有效开始,实际上它不是。

您返回的是 HTML 页面(可能包含错误信息)。

从文本中我了解到您创建了 2 个独立的项目。这意味着 "api/emps/" 不是有效的路线。您的 API 和客户可能正在 运行 宁 localhost:xxxx 和 localhost:yyyy .

修复该路由后,您可能 运行 会遇到 CORS 问题,请在您的服务器上进行配置。

请注意,当您创建 Blazor Webassembly 应用并选中 'Hosted' 框时,会为此提供基本设置。


尝试

empList = await Http.GetJsonAsync<Emp[]>("https://localhost:44333/api/emps"); 

并在您的服务器中 Startup.Configure()

app.UseCors(policy => 
    policy.WithOrigins("https://localhost:44399")  // client address 
    .AllowAnyMethod()
    .WithHeaders(HeaderNames.ContentType));