首页 > 解决方案 > Crit 错误未处理的异常渲染组件

问题描述

我是 Blazor 的新手,但我有一个可路由的组件。它调用一个允许匿名的 api 端点。据我了解,Blaozr WASM 会自动将标头中的令牌附加到每个 http 请求,因此,在我的 Blazor WASM HttpService 中,我有两个 httpClient 设置,一个用于匿名,一个用于调用令牌的 http。

以登录用户的身份前往该路线工作正常,在未登录的情况下前往该路线会产生以下错误,但我不知道为什么。此外,我尝试在所有相关部分(http 服务、组件类)放置断点,并且没有一个断点被命中。我在组件中放了一个断点,user.Identity.isAuthenticated它仍然没有被命中。该页面只是在控制台中加载该错误。有什么指导吗?如果断点拒绝被兑现,我不确定如何有效地调试它,哈哈。

Program.CS 有:

builder.Services.AddHttpClient("Quillerz.AnonAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
              .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

builder.Services.AddHttpClient("Quillerz.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress))
                .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

组件代码:

@page "/communities/{CommunityId:guid}"
@using Quillerz.Shared.Communities
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject AuthenticationStateProvider AuthenticationStateProvider
@inject Quillerz.Client.Services.ICommunityHttpService CommunityService
@inject NavigationManager Navigation
@inject NotificationService NotificationService


@if (Community != null)
{
    <div class="container">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <div class="d-flex w-100 justify-content-between">
                            <h5 class="card-title">@Community.Name</h5>
                            <span class="text-muted">@Community.MemberCount members</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
}
else
{
    <span>Couldn't find community.</span>
}

@code {
    [Parameter]
    public Guid CommunityId { get; set; }

    private CommunityDto Community { get; set; } = new CommunityDto();

    protected override async Task OnInitializedAsync()
    {
        if (!string.IsNullOrEmpty(CommunityId.ToString()))
        {
            var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;

            if (user.Identity.IsAuthenticated)
            {
                Community = await CommunityService.GetCommunity(CommunityId, true);
            }
            else
            {
                Community = await CommunityService.GetCommunity(CommunityId, false);
            }
        }
        else
        {
            NotificationMessage errMsg = new NotificationMessage()
            {
                Severity = NotificationSeverity.Error,
                Summary = "Whoops!",
                Detail = "Couldn't find the community id.",
                Duration = 4000
            };
            NotificationService.Notify(errMsg);
        }
    }
}

服务:

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("Quillerz.AnonAPI");
}

public async Task<CommunityDto> GetCommunity(Guid communityId, bool userIsAuthenticated)
{
    if (!userIsAuthenticated)
    {
       return await anonHttp.GetFromJsonAsync<CommunityDto>($"api/communities/" + communityId);
    }
    else
    {
       return await httpClient.GetFromJsonAsync<CommunityDto>($"api/communities/" + 
          communityId);
    }
}

控制台中的完整错误:

blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: ''
Microsoft.AspNetCore.Components.WebAssembly.Authentication.AccessTokenNotAvailableException: ''
   at Microsoft.AspNetCore.Components.WebAssembly.Authentication.AuthorizationMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at Microsoft.Extensions.Http.Logging.LoggingScopeHttpMessageHandler.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
   at System.Net.Http.Json.HttpClientJsonExtensions.<GetFromJsonAsyncCore>d__9`1[[Quillerz.Shared.Communities.CommunityDto, Quillerz.Shared, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].MoveNext()
   at Quillerz.Client.Services.CommunityHttpService.GetCommunity(Guid communityId, Boolean userIsAuthenticated) in C:\Code\Quillerz\Quillerz\Quillerz\Client\Services\CommunityHttpService.cs:line 45
   at Quillerz.Client.Pages.CommunityDetail.OnInitializedAsync() in C:\Code\Quillerz\Quillerz\Quillerz\Client\Pages\CommunityDetail.razor:line 51
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle)

标签: blazorblazor-webassembly

解决方案


有点晚了,但我在 Blazor WASM 中遇到了同样的问题。就我而言,我需要保护我的剃须刀组件,例如:@attribute [Authorize(Roles="admin")]. 在此之后它工作正常。


推荐阅读