ConfirmEmail页面重定向首页报错,如何正确跳转至首页?
解决Razor Pages中ConfirmEmail页面重定向首页的异常问题
你遇到的这个问题是Razor Pages里RedirectToPage方法的路径写法不正确导致的。在Razor Pages中,直接使用/Index作为页面名称会找不到对应的页面文件,因为方法对路径的解析规则和你想的不一样。
正确的重定向写法有两种:
- 写法一:直接指定页面名称
如果你首页是根目录下的Index.cshtml,直接传入页面名称"Index"即可:return RedirectToPage("Index"); - 写法二:使用根路径简写
因为Razor Pages默认会把根路径"/"映射到Index页面,所以也可以这样写:return RedirectToPage("/");
修改后的完整代码
把你原来的错误代码行替换后,ConfirmEmail页面的OnGetAsync方法应该是这样:
public async Task<IActionResult> OnGetAsync(string userId, string code) { if (userId == null || code == null) { return RedirectToPage("Index"); // 或者 return RedirectToPage("/"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return NotFound($"Unable to load user with ID '{userId}'."); } code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); var result = await _userManager.ConfirmEmailAsync(user, code); StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email."; return Page(); }
为什么原来的写法会报错?
在Razor Pages的RedirectToPage方法中,当你传入以/开头的路径时,它会从应用根目录查找对应的页面文件,但正确的页面路径应该是不带多余前缀的。/Index这种写法会让框架去寻找一个名为/Index的页面(而实际你的页面是Index.cshtml,对应路由是/Index,但方法参数需要的是页面名称或者正确的路由段),所以才会抛出InvalidOperationException: No page named '/Index' matches the supplied values的异常。
内容的提问来源于stack exchange,提问作者ZedZip
相关产品推荐
相关产品推荐

