You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server .NET 8获取ApplicationUser触发NullReferenceException求助

问题排查与解决

可能的原因及对应修复方法

1. 缺少身份验证布局或授权标记

你的/Account/ISP页面可能未使用与Manage页面相同的布局,也未添加授权约束,导致无法正确获取已登录用户的上下文:

  • 添加[Authorize]属性限制仅登录用户访问,同时指定Account布局(与Manage页面保持一致):
@page "/Account/ISP"
@layout AccountLayout
@attribute [Authorize]
@using Microsoft.AspNetCore.Identity
@using WebApp.Components.Account.Shared
@using WebApp.Data

@inject UserManager<ApplicationUser> UserManager
@inject SignInManager<ApplicationUser> SignInManager
@inject IdentityUserAccessor UserAccessor
@inject IdentityRedirectManager RedirectManager
@inject ApplicationDbContext DbContext

2. 级联HttpContext为空

Blazor Server中,级联的HttpContext并非在所有场景下都能稳定获取,尤其是页面未被身份验证管道正确处理时。可以替换为直接通过UserManager获取用户:

protected override async Task OnInitializedAsync()
{
    var currentPrincipal = HttpContext.User;
    if (!currentPrincipal.Identity?.IsAuthenticated ?? true)
    {
        RedirectManager.RedirectToLogin();
        return;
    }
    user = await UserManager.GetUserAsync(currentPrincipal) ?? throw new InvalidOperationException("无法找到当前登录用户");
}

3. 检查IdentityUserAccessor的实现逻辑

如果项目中的IdentityUserAccessor是自定义实现,确认其GetRequiredUserAsync方法在用户不存在时是否会抛出异常而非返回null。若方法本身存在空引用漏洞,需调整实现逻辑确保返回有效用户对象或正确抛出异常。

内容的提问来源于stack exchange,提问作者SelfishCrawler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 14:17:39