Response.Redirect using ~ Path

后端 未结 3 953
星月不相逢
星月不相逢 2020-12-14 00:34

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:



        
相关标签:
3条回答
  • 2020-12-14 01:16

    you can resolve the URL first Response.Redirect("~/Login.aspx); and add the parameters after it got resolved.

    0 讨论(0)
  • 2020-12-14 01:22

    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));
    
    0 讨论(0)
  • 2020-12-14 01:30

    What about using

    Response.Redirect(String.Format("http://{0}/Login.aspx?ReturnPath={1}", Request.ServerVariables["SERVER_NAME"], Request.Url.ToString()));
    
    0 讨论(0)
提交回复
热议问题