33

With ASP.Net Core 2.1 Razor Pages, what is the best practice on using LocalRedirect() vs. RedirectToPage()?

It seems they can be used interchangeably when redirecting to a page within the current website. Is there an advantage to one over the other?

urig
  • 16,016
  • 26
  • 115
  • 184
  • 2
    In addition to Chris's answer, it's worth noting that `RedirectToPage` uses a path representing the Page as it sits within the filesystem, whereas `LocalRedirect` uses a local URL. Using `RedirectToPage` would ensure that if you modify the routing for a page, for example, then the URL that was generated would match the correct route. – Kirk Larkin Aug 27 '18 at 17:16

1 Answers1

56

LocalRedirect should be used when you're dealing with a "return URL", i.e. you're passing around a URL that the user should be redirected back to after some process is complete, such as logging in. In such cases, a malicious actor could send a user to your login form, for example, with a return URL back to a malicious site. Using LocalRedirect ensures that the "return URL" is a route actually on your site, instead of some malicious third-party bad actor's.

All the other redirect result types can be used when you are directly controlling where the user is being redirected to.

Chris Pratt
  • 232,153
  • 36
  • 385
  • 444
  • 1
    Isnt `RedirectToPage` just as safe as `LocalRedirect`? Since it only works for local page paths? If so, isnt your point about **only** using `LocalRedirect` when you dont control the return url wrong? – Andriod Apr 27 '19 at 19:12
  • 3
    It perhaps wasn't explicit in my answer, but the key point is the return URL, not the local-only safety. RedirectToPage would require knowledge of the exact page, which is not something you would expose as part of the return URL you're passing between requests. In other words, you use RedirectToPage when you're redirecting explicitly to a certain page. You use LocalRedirect, when it's just a string URL value that may or may not map to a particular page. – Chris Pratt Apr 28 '19 at 00:58
  • What do you mean with passing a value that doesn't map into a particular page into `LocalRedirect`? What is the expected behavior then? – Yola Apr 25 '21 at 15:28
  • 2
    @yola It could be a controller action, for example, in which case you couldn't even use RedirectToPage if you wanted to. It's also not validated that you can route to it, like RedirectToPage. You could attach /path/to/nowhere as the returnURL, and that will pass through LocalRedirect (because it's local), but of course, it would result in a 404. – Chris Pratt Apr 25 '21 at 15:33