未处理的异常渲染组件:“<”是 Blazor WASM 值的无效开头

J.G*_*ble 8 blazor blazor-webassembly

我有一个允许匿名的 API 端点。我已经在 Postman 中确认它适用于匿名和经过身份验证的用户并返回正确的 JSON。

由于可以匿名调用端点,因此在我的 Blazor WASM http 服务中,我构建了以下内容:一个不带令牌发送的请求,一个带令牌发送的请求。

private readonly HttpClient httpClient;
private readonly IHttpClientFactory httpClientFactory;
private readonly HttpClient anonHttp;

public CommunityHttpService(HttpClient httpClient, IHttpClientFactory httpClientFactory)
{
   if (httpClient == null) throw new ArgumentNullException("Http is null.");
   this.httpClient = httpClient;
   this.httpClientFactory = httpClientFactory;
   anonHttp = httpClientFactory.CreateClient("AnonAPI");
}

public async Task<HttpResponseMessage> GetCommunity(Guid communityId, bool userIsAuthenticated)
{
    if (!userIsAuthenticated)
    {
       // make anonymous api call without bearer token to avoid error
       return await anonHttp.GetAsync($"api/communities/GetCommunity/" + communityId);
    }
    else
    {
       return await httpClient.GetAsync($"api/communities/GetCommunity/" + communityId);
     }
}
Run Code Online (Sandbox Code Playgroud)

我在我的组件中声明了社区。

private CommunityDto Community { get; set; } = new CommunityDto();
Run Code Online (Sandbox Code Playgroud)

在组件的 OnInitializedAsync 方法中,我有以下内容:

if (!string.IsNullOrEmpty(CommunityId.ToString()))
{
    var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
    var user = authState.User;
    HttpResponseMessage apiResponse;
    if (user.Identity.IsAuthenticated)
    {
       apiResponse = await CommunityService.GetCommunity(CommunityId, true);
    }
    else
    {
      apiResponse = await CommunityService.GetCommunity(CommunityId, false);
    }

    if (apiResponse.IsSuccessStatusCode)
    {
        Community = await apiResponse.Content.ReadFromJsonAsync<CommunityDto>();
    }
}
Run Code Online (Sandbox Code Playgroud)

所有的html都是:

<span>@CommunityId</span>
Run Code Online (Sandbox Code Playgroud)

设置断点似乎没有用,但我不知道是什么原因导致控制台中出现此错误。有任何想法吗?

Yan*_*ann 21

这是因为您正在运行 blazor xxxx.Client 项目而不是 xxxx.Server 项目。

在第一种情况下,var Forecasts = wait _http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast"); 将转到“本地”客户端项目(即 BalzorWASM pwa)中的某个位置,因此无法找到此资源,因此您可能会收到一个 html 错误页面“抱歉,此地址上没有任何内容。”。

在第二种情况下,var Forecasts = wait _http.GetFromJsonAsync<WeatherForecast[]>("WeatherForecast"); 适用于服务器部分,在那里,您的控制器就可以了。

首先,浏览 WeatherForecast 将使您进入“抱歉,该地址没有任何内容”页面,其次,您将看到 WeatherForecast 控制器响应。

这就是为什么它说它无法反序列化以“<”开头的内容,而“<”实际上是标签。

  • 确实启动项目必须是服务器 (2认同)

Hen*_*man 8

该错误表明开始标记<html>不是有效的 JSon。

这意味着这"api/communities/GetCommunity/"是不正确的。或者在 Program.cs 中配置的 BaseAddress 。

使用开发工具的“网络”选项卡查看正在使用的 URL,并将其与您在 PostMan 中使用的 URL 进行比较。

由于 Blazor Wasm 应用程序中的路由,您不会从 API 收到 404 返回,但您会收到“此处无内容”的 Blazor 后备页面。