首页 > 解决方案 > 如何在 blazor wabassembly 应用程序中找到错误(很难找到错误)

问题描述

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

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

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

API 响应

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

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

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 路径错误?

看我的控制台日志非常非常难找到错误?

标签: c#blazorblazor-client-sideblazor-webassembly

解决方案


该错误是关于<不是 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));

推荐阅读