Blazor Server Cookie认证后出现NavigationException,如何正确处理登录重定向?
在Blazor Server应用中实现Cookie认证,登录成功后出现以下错误:
NavigationException: Exception of type 'Microsoft.AspNetCore.Components.NavigationException' was thrown.
尽管满足以下条件,重定向到/home仍失败:
- Cookie创建成功
- 已正确设置Claims
SignInAsync过程无错误
Login.razor代码
<EditForm Model="Model" OnValidSubmit="LoginUserAsync" FormName="LoginUser" id="formAuthentication" class="mb-5"> <DataAnnotationsValidator /> <div class="form-floating form-floating-outline mb-5"> <InputText @bind-Value="Model.UserName" class="form-control" id="email" placeholder="Enter your email or username" /> <label for="email">Email or UserName</label> <ValidationMessage For="@(() => Model.UserName)" /> </div> <div class="mb-5"> <div class="form-password-toggle"> <div class="input-group input-group-merge"> <div class="form-floating form-floating-outline"> <InputText @bind-Value="Model.Password" type="password" id="password" class="form-control" placeholder="********" /> <label for="password">Password</label> </div> <span class="input-group-text cursor-pointer"> <i class="ri-eye-off-line"></i> </span> </div> <ValidationMessage For="@(() => Model.Password)" class="validation-message mt-1 ml-1" /> </div> </div> <div class="mb-5"> <button type="submit" class="btn btn-primary d-grid w-100 login-btn" disabled="@EnableLoading" value="Sign In"> @if (EnableLoading) { <span class="spinner-border spinner-border-sm" role="status"></span> } Sign In </button> </div> </EditForm>
Program.cs配置代码
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(options => { options.LoginPath = "/login"; options.Cookie.HttpOnly = true; });
Login.razor.cs代码
private async Task LoginUserAsync() { await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties); Navigation.NavigateTo("/home", forceLoad: true); // 此处抛出异常 }
已尝试的解决方案
- 添加
AuthenticationStateProvider通知——无效果 - 在
NavigateTo中使用forceLoad: true——仍抛出相同异常 - 尝试JS的
location.assign()——可行但会中断Blazor回路 - 验证中间件顺序正确(UseRouting > UseAuthentication > UseAuthorization)
完整异常信息
Microsoft.AspNetCore.Components.NavigationException: Exception of type 'Microsoft.AspNetCore.Components.NavigationException' was thrown.
at Microsoft.AspNetCore.Components.Routing.NavigationManager.AssertInitialized()
at Microsoft.AspNetCore.Components.Routing.NavigationManager.NavigateToCore(String uri, Boolean forceLoad)
内容的提问来源于stack exchange,提问作者Ko Ko Naing
相关产品推荐
相关产品推荐

