.NET 8 Blazor项目:基于.NET Identity的OTP自动登录重定向报错处理
Blazor SSR中OTP自动登录后重定向报错的解决方法
我正在开发一个基于.NET 8 Blazor、采用.NET Identity认证的项目,需求是在OnInitializedAsync方法中,通过查询参数传入的OTP实现用户自动登录并完成重定向。
原实现代码
[SupplyParameterFromQuery] private string Otp { get; set; } = default!; [Inject] SignInManager<ApplicationUser> SignInManager { get; set; } = default!; protected override async Task OnInitializedAsync() { try { if (HttpMethods.IsGet(HttpContext.Request.Method)) { await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); } if (!string.IsNullOrEmpty(Otp)) { // 验证OTP并获取用户和声明 await SignInManager.SignInWithClaimsAsync(user, isPersistent: false, claims); NavigationManager.NavigateTo("/test"); } else { NavigationManager.NavigateTo("/error"); } await base.OnInitializedAsync(); } catch (Exception) { NavigationManager.NavigateTo("/error"); } }
遇到的异常
执行重定向时抛出以下异常:
Microsoft.AspNetCore.Components.NavigationException: 'Exception of type 'Microsoft.AspNetCore.Components.NavigationException' was thrown.'
可行解决方案
问题出在Blazor SSR场景下,NavigationManager.NavigateTo不适合在服务端初始化阶段直接使用。通过扩展HttpContext实现服务端原生重定向,兼容Blazor增强导航:
扩展方法代码
public static class BlazorSsrRedirectManagerExtensions { public static void RedirectTo(this HttpContext httpContext, string redirectionUrl) { ArgumentNullException.ThrowIfNull(httpContext); httpContext.Response.Headers.Append("blazor-enhanced-nav-redirect-location", redirectionUrl); httpContext.Response.StatusCode = 200; httpContext.Response.Redirect(redirectionUrl); } }
修改原逻辑
将原代码中的NavigationManager.NavigateTo调用替换为HttpContext.RedirectTo,并在重定向后直接返回,避免后续代码执行:
protected override async Task OnInitializedAsync() { try { if (HttpMethods.IsGet(HttpContext.Request.Method)) { await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); } if (!string.IsNullOrEmpty(Otp)) { // 验证OTP并获取用户和声明 await SignInManager.SignInWithClaimsAsync(user, isPersistent: false, claims); HttpContext.RedirectTo("/test"); return; // 重定向后退出方法 } else { HttpContext.RedirectTo("/error"); return; } await base.OnInitializedAsync(); } catch (Exception) { HttpContext.RedirectTo("/error"); return; } }
内容的提问来源于stack exchange,提问作者Coder3000
相关产品推荐
相关产品推荐

