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

问题描述

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

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

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

API response

当我在客户端调用webapi时,发现错误非常困难

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

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**
}

Browser screenshot with error

什么类型的错误

我的webapi路径错误吗?

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

解决方法

错误与<不是Json响应的有效开始有关,实际上并非如此。

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

根据我收集的文字,您创建了2个独立的项目。这意味着"api/emps/"不能为有效路由。您的API和客户端可能正在localhost:xxxx和localhost:yyyy上运行。

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

请注意,当您创建Blazor Webassembly应用程序并选中“托管”框时,将为此提供基本设置。


尝试

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));