2

I am passing the returnUrl = Request.Url to a controller action, the problem is that when I check it with the following code before redirecting, it fails because of the IsLocalUrl() call. Why?

if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
   {
      return Redirect(returnUrl);
   }

Thanks.

abenci
  • 8,422
  • 19
  • 69
  • 134
  • It's failing in the sense that returns false? May it be something related to this SO question: http://stackoverflow.com/questions/8633782/why-does-url-islocalurl-return-false-if-the-url-contains-a-fragment ? – Tallmaris Aug 27 '14 at 08:14
  • Yes, and the URL is absolutely fine: `http://localhost:55058/Orders/Details/102064`. What exactly means 'local' in this context? – abenci Aug 27 '14 at 08:33
  • Looking at the `IsReturnUrl` implementation (https://aspnetwebstack.codeplex.com/SourceControl/latest#src/System.Web.WebPages/RequestExtensions.cs), it seems to consider local only things that start with `/` and `~/` (but not `//` or `/\`. You should probably trim the protocol:domain part of the url... – Tallmaris Aug 27 '14 at 09:11
  • 1
    Note that the above is a change in MVC after 3 I think, since in MVC3 (as the SO answer explains) using absolute URL will work. – Tallmaris Aug 27 '14 at 09:12
  • How do I get a local URL from `Request` class? I also tried `Request.RawUrl()` without success. – abenci Aug 27 '14 at 09:37
  • Best option is to create a new `Uri` object (http://msdn.microsoft.com/en-us/library/system.uri(v=vs.110).aspx) and get the path: `new Uri(returnUrl).AbsolutePath` and pass this into `IsLocalUrl()` – Tallmaris Aug 27 '14 at 14:07

1 Answers1

8

The problem was simply that Url.IsLocalUrl() returns true for URLs like /Orders/Details/5326 and false for URLs like http://www.company.com/Orders/Details/5326

abenci
  • 8,422
  • 19
  • 69
  • 134
  • To explain the problem: That method checks if url is a relative url. If it's an absolute url, that method retuns false. – Michael Aug 13 '19 at 10:23