Blazor .NET 8登录页HttpContext返回Null的问题求助
Blazor Web App .NET 8登录页面空引用异常排查方案
问题背景
上周开发Blazor Web App .NET 8项目时登录功能正常,现在返回项目后登录页面抛出空引用异常,报错指向HttpContext为null。
Login.razor代码
@page "/Account/Login" @layout EmptyLayout @attribute [AllowAnonymous] @using System.ComponentModel.DataAnnotations @using AVAZicht.Components.Layout @using Microsoft.AspNetCore.Authentication @using Microsoft.AspNetCore.Identity @using AVAZicht.Data @inject SignInManager<ApplicationUser> SignInManager @inject ILogger<Login> Logger @inject NavigationManager NavigationManager @inject IdentityRedirectManager RedirectManager <PageTitle>Log in</PageTitle> <div class="container"> <div class="row justify-content-md-center align-items-center vh-100"> <div class="col-lg-4" align="center"> <img src="images/ava_logo_transp.png" class="w-75 mb-3" /> <section class="p-0"> <StatusMessage Message="@errorMessage" /> <EditForm Model="Input" method="post" OnValidSubmit="LoginUser" FormName="login"> <DataAnnotationsValidator /> <ValidationSummary class="text-danger" role="alert" /> <div class="form-floating mb-3"> <InputText @bind-Value="Input.Email" class="form-control" autocomplete="username" aria-required="true" placeholder="name@example.com" /> <label for="email" class="form-label">Email</label> <ValidationMessage For="() => Input.Email" class="text-danger" /> </div> <div class="form-floating mb-3"> <InputText type="password" @bind-Value="Input.Password" class="form-control" autocomplete="current-password" aria-required="true" placeholder="password" /> <label for="password" class="form-label">Password</label> <ValidationMessage For="() => Input.Password" class="text-danger" /> </div> <div class="checkbox mb-3"> <label class="form-label"> <InputCheckbox @bind-Value="Input.RememberMe" class="darker-border-checkbox form-check-input" /> Ingelogd blijven </label> </div> <div> <button type="submit" class="w-100 btn btn-lg btn-primary">Inloggen</button> </div> </EditForm> </section> </div> </div> </div> @code { private string? errorMessage; [CascadingParameter] private HttpContext HttpContext { get; set; } = default!; [SupplyParameterFromForm] private InputModel Input { get; set; } = new(); [SupplyParameterFromQuery] private string? ReturnUrl { get; set; } protected override async Task OnInitializedAsync() { if (HttpMethods.IsGet(HttpContext.Request.Method)) { // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); } } public async Task LoginUser() { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await SignInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { Logger.LogInformation("User logged in."); RedirectManager.RedirectTo(ReturnUrl); } else if (result.RequiresTwoFactor) { RedirectManager.RedirectTo( "Account/LoginWith2fa", new() { ["returnUrl"] = ReturnUrl, ["rememberMe"] = Input.RememberMe }); } else if (result.IsLockedOut) { Logger.LogWarning("User account locked out."); RedirectManager.RedirectTo("Account/Lockout"); } else { errorMessage = "Error: Invalid login attempt."; } } private sealed class InputModel { [Required] [EmailAddress] public string Email { get; set; } = ""; [Required] [DataType(DataType.Password)] public string Password { get; set; } = ""; [Display(Name = "Remember me?")] public bool RememberMe { get; set; } } }
报错信息
System.NullReferenceException: 'Object reference not set to an instance of an object.' AVAZicht.Components.Account.Pages.Login.HttpContext.get returned null.
排查思路
- 检查组件渲染模式:
HttpContext仅能在服务器渲染模式(SSR)或交互式服务器组件中获取。若Login组件添加了@rendermode InteractiveWebAssembly属性,会导致HttpContext为null。对比新项目的登录页(默认SSR),移除该属性或改为InteractiveServer。 - 确认HttpContext级联传递:检查App.razor是否包含
CascadingAuthenticationState,确保HttpContext能正确级联到子组件。新项目的App.razor通常会有如下结构:
同时检查EmptyLayout布局是否阻断了级联参数传递。<CascadingAuthenticationState> <Router AppAssembly="@typeof(App).Assembly"> <!-- 路由内容 --> </Router> </CascadingAuthenticationState> - 对比认证配置:检查Program.cs中的认证服务配置,确保
AddAuthentication、AddIdentity等服务正确注册,且UseAuthentication()、UseAuthorization()在UseRouting()之后、UseEndpoints()之前调用,与新项目配置保持一致。 - 清理重建项目:删除bin/obj文件夹,重启开发环境,重新生成解决方案,排除缓存导致的异常。
- 检查EmptyLayout布局:确认EmptyLayout没有设置错误的渲染模式,且没有覆盖或阻断
HttpContext的级联传递。
内容的提问来源于stack exchange,提问作者Jeremy
相关产品推荐
相关产品推荐

