[英]Response.Redirect using ~ Path
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. 我有一个方法,我想将用户重定向回位于我的Web应用程序根目录的登录页面。
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. 我的假设是ASP.NET会自动将URL解析为正确的路径。 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? 我该如何解决这个问题?
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. :-)除非您想对您的Web应用程序进行硬编码,以便它只能安装在网站的根目录下。
"~/" 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 (eg "** 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. “〜/” 是正确使用的东西,但原始代码没有按预期工作的原因是ResolveUrl
(由Redirect
内部使用)尝试首先计算出你传递它的路径是绝对的URL(例如“** http:// server / ** foo / bar.htm”而不是“foo / bar.htm”) - 但不幸的是,它通过在URL中查找冒号字符':'来实现此目的你给它。 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. 但在这种情况下,它会在您在ReturnPath
查询字符串值中给出的URL中找到一个冒号,这会ReturnPath
它 - 因此您的'〜/'无法解析。
The fix is that you should be URL-encoding the ReturnPath
value which escapes the problematic ':' along with any other special characters. 修复是您应该对ReturnPath
值进行URL编码,该值可以转义有问题的':'以及任何其他特殊字符。
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). 另外,我建议你(或任何人)永远不要使用Uri.ToString
- 因为它提供了一个人类可读,更“友好”的URL版本 - 不一定是正确的(它可以解决问题)。 Instead use Uri.AbsoluteUri - like so: 而是使用Uri.AbsoluteUri - 像这样:
Response.Redirect("~/Login.aspx?ReturnPath=" + Server.UrlEncode(Request.Url.AbsoluteUri));
您可以先解析URL Response.Redirect(“〜/ Login.aspx);并在解析后添加参数。
怎么样使用
Response.Redirect(String.Format("http://{0}/Login.aspx?ReturnPath={1}", Request.ServerVariables["SERVER_NAME"], Request.Url.ToString()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.