views:

2365

answers:

3

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?

+1  A: 

What about using

Response.Redirect(String.Format("http://{0}/Login.aspx?ReturnPath={1}", Request.ServerVariables["SERVER_NAME"], Request.Url.ToString()));
Marshall
+1  A: 

To translate a ~ (tilde) into a usable path, use ResolveUrl.

bdukes
+11  A: 

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 of 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));
Duncan Smart