Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor Pages RedirectToPage("/") causes error "No page named '/' matches the supplied values"

Tags:

razor-pages

In a brand new out-of-the-box asp.net core RazorPages project, why does the following result in the exception "InvalidOperationException: No page named '/' matches the supplied values"?

public IActionResult OnPost()
{
    return RedirectToPage("/");
}

I would expect it to redirect to /Index. RedirectToPage("") and RedirectToPage("Index") work as expected, but in this case I'm being passed a return url of "/". I know I could just check for "/" and replace it with "" but it seems like this should work.

like image 807
Rob Harris Avatar asked Jun 13 '20 10:06

Rob Harris


1 Answers

The RedirectToPage() method is referring to a Razor cshtml "page" rather than a html page in the browser. So it expects the parameter to refer to a cshtml page in your project. e.g.

public IActionResult OnPost()
{
    // Redirect to Index.cshtml in folder above
    return RedirectToPage("../Index");
}

That's why "/" is not valid with this method.

If you want to redirect to a url you can use Redirect() e.g.

public IActionResult OnPost()
{
    return Redirect("~/");
}
like image 191
Rosco Avatar answered Sep 18 '22 10:09

Rosco