Blazor Server项目中HeadOutlet组件抛出System.NullReferenceException的问题求助
Blazor Server项目中HeadOutlet组件抛出System.NullReferenceException的问题求助
我最近在搭建Blazor Server项目时碰到了一个棘手的空引用异常,想请教大家原因和解决办法,以下是我的操作流程和问题详情:
项目搭建与配置步骤
- 首先用MudBlazor官方模板创建项目:
dotnet new install MudBlazor.Templates dotnet new mudblazor --host Server --name MyApplication - 将项目目标框架(TFM)从net6.0升级到net7.0,同时更新了所有NuGet包
- 配置Cookie认证:添加了Cookie认证相关逻辑,在
_Imports.razor中加入@attribute [Authorize],还编写了一个负责跳转登录页的组件 - 修改
App.razor,替换为包含AuthorizeRouteView的路由逻辑,代码如下:@inject NavigationManager Navigation <CascadingAuthenticationState> <Router AppAssembly="@typeof(App).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"> <NotAuthorized> @if (!context.User?.Identity?.IsAuthenticated ?? false) { <RedirectToLogin ReturnUrl="@Navigation.ToBaseRelativePath(Navigation.Uri)" /> } else { <p role="alert">Sorry, you're not authorized to view this page.</p> } <MudText Typo="Typo.h3">Access Denied</MudText> </NotAuthorized> <Authorizing> <MudText Typo="Typo.h3" GutterBottom="true">Authorization in progress...</MudText> </Authorizing> </AuthorizeRouteView> <FocusOnNavigate RouteData="@routeData" Selector="h1" /> </Found> <NotFound> <PageTitle>Not found</PageTitle> <LayoutView Layout="@typeof(MainLayout)"> <p role="alert">Sorry, there's nothing at this address.</p> </LayoutView> </NotFound> </Router> </CascadingAuthenticationState> - 最后添加了触发登录跳转的组件,代码如下:
@using System.Web; @inject NavigationManager Navigation @code { [Parameter] public string ReturnUrl { get; set; } = null!; protected override async Task OnInitializedAsync() { var loginEndpoint = "Login?redirectUri=" + HttpUtility.UrlEncode(ReturnUrl); Navigation.NavigateTo(loginEndpoint, forceLoad: true); await base.OnInitializedAsync(); } }
遇到的异常问题
完成上述配置后,项目运行时会在_Layout.cshtml的这一行抛出System.NullReferenceException:
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />
更奇怪的是,当我把App.razor中<NotAuthorized>区块里的<MudText Typo="Typo.h3">Access Denied</MudText>这一行删掉后,这个空引用异常就消失了。
有没有大佬能帮忙解释下为什么会出现这种情况?以及该怎么解决才能保留这个提示文本同时避免异常呢?
备注:内容来源于stack exchange,提问作者Victorio Berra
相关产品推荐
相关产品推荐

