如何重定向到首页?

时间:2020-01-09 12:34:43

标签: asp.net-core razor-pages blazor

ConfirmEmail页面包含:

public async Task<IActionResult> OnGetAsync(string userId, string code)
{
    if (userId == null || code == null)
    {
        return RedirectToPage("/Index"); // <----------error
    }

    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();
}

但是当我测试它的空参数时,它将尝试重定向到页面 返回RedirectToPage(“ / Index”);

它会生成异常:

处理请求时发生未处理的异常。 InvalidOperationException:没有名为“ / Index”的页面与提供的页面匹配 值

如何重定向到主页?

3 个答案:

答案 0 :(得分:1)

Blazor 中,您应该使用Microsoft.AspNetCore.Components.NavigationManager

@inject NavigationManager NavigationManager

if (userId == null || code == null)
    {
        NavigationManager.NavigateTo("/Index"); // <----------error
    }

答案 1 :(得分:0)

如果页面位于不同的文件夹中,它将以这种方式工作

return Redirect("~/");

答案 2 :(得分:0)

RedirectToPage()返回一个IActionResult,该HTTP通过给出 Razor页面的路径,将HTTP重定向到您指定的路由。剃刀页面是.cshtml文件夹中的Pages文件。

如果您使用的是Blazor,则很可能会使用其随附的客户端路由器。在这种情况下,只有一个Razor页面_Host.cshtml将用作Blazor应用程序的主要入口点。

所以您可以可以做的是重定向到/_Host,尽管我不建议这样做。相反,仅重定向到应用程序的根目录,询问服务器端端点路由器的路由可能是最好的主意:

return LocalRedirect("/");