I have a method that where I want to redirect the user back to a login page located at the root of my web application.
I'm using the following code:
Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString());
This doesn't work though. My assumption was that ASP.NET would automatically resolve the URL into the correct path. Normally, I would just use
Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString());
but this code is on a master page, and can be executed from any folder level. How do I get around this issue?
"~/" is the correct thing to use, but the reason that your original code didn't work as expected is that ResolveUrl (which is used internally by Redirect ) tries to first work out if the path you are passing it is an absolute URL (e.g. "**http://server/**foo/bar.htm" as opposed to "foo/bar.
Response. Redirect sends an HTTP request to the browser, then the browser sends that request to the web server, then the web server delivers a response to the web browser. For example, suppose you are on the web page "UserRegister. aspx" page and it has a button that redirects you to the "UserDetail.
For instance, instead of a "form" button that causes a postback and redirect, you could use a LinkButton that will behave like a hyperlink, allowing the browser to request the new page directly.
Response. Redirect simply sends a message (HTTP 302) down to the browser. Server. Transfer happens without the browser knowing anything, the browser request a page, but the server returns the content of another.
I think you need to drop the "~/" and replace it with just "/", I believe / is the root
STOP RIGHT THERE! :-) unless you want to hardcode your web app so that it can only be installed at the root of a web site.
"~/" is the correct thing to use, but the reason that your original code didn't work as expected is that ResolveUrl
(which is used internally by Redirect
) tries to first work out if the path you are passing it is an absolute URL (e.g. "**http://server/**foo/bar.htm" as opposed to "foo/bar.htm") - but unfortunately it does this by simply looking for a colon character ':' in the URL you give it. But in this case it finds a colon in the URL you give in the ReturnPath
query string value, which fools it - therefore your '~/' doesn't get resolved.
The fix is that you should be URL-encoding the ReturnPath
value which escapes the problematic ':' along with any other special characters.
Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.ToString()));
Additionally, I recommend that you (or anyone) never use Uri.ToString
- because it gives a human-readable, more "friendly" version of the URL - not a necessarily correct one (it unescapes things). Instead use Uri.AbsoluteUri - like so:
Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.AbsoluteUri));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With