Response.Redirect的使用〜路径 [英] Response.Redirect using ~ Path
问题描述
我有,我想将用户重定向回位于我的web应用程序的根目录的登录页面的方法。
我用下面的code:
的Response.Redirect(〜/的Login.aspx ReturnPath这样=?+ Request.Url.ToString());
这不,虽然工作。我的假设是,ASP.NET会自动解析URL到正确的路径。通常情况下,我只想用
的Response.Redirect(../的Login.aspx ReturnPath这样=?+ Request.Url.ToString());
但这种code是一个母版页,并且可以从任何文件夹级别执行。我该如何解决此问题得到什么?
我认为你需要删除〜/,并不仅仅是/代替它,我相信/是根
块引用>停在那儿! :-),除非你想硬code你的web应用程序,以便它可以只在一个网站的根目录进行安装。
〜/ 是的的正确的事情来使用,但如预期你原来的code没有工作的原因是,
RESOLVEURL
(这是由重定向内部使用
)尝试先制定出如果你传递给它的路径是一个绝对URL(例如 *的的http://服务器/ 的*富/ bar.htm,而不是富/ bar.htm) - 但不幸的是它通过简单地寻找一个冒号字符做到这一点:在''网址你给它。但在这种情况下,它发现在你的ReturnPath这样
查询字符串值给URL,这是傻瓜一个冒号 - 所以,你们的'〜/'没有得到解决<。 / p>解决方法是,你应该URL编码它逃逸的问题在
ReturnPath这样
值:与其他任何特殊字符一起的Response.Redirect(?〜/的Login.aspx ReturnPath这样=+ Server.UrlEn code(Request.Url.ToString()));
此外,我建议你(或任何人)从来不使用
Uri.ToString
- 因为它给人类可读,更友好的URL的版本 - 不一个必然正确的(未逸出它的东西)。而是使用Uri.AbsoluteUri - 像这样:的Response.Redirect(?〜/的Login.aspx ReturnPath这样=+ Server.UrlEn code(Request.Url.AbsoluteUri));
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?
解决方案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 byRedirect
) 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 theReturnPath
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));
这篇关于Response.Redirect的使用〜路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!