Redirect的使用〜路径

Redirect的使用〜路径

本文介绍了Response.Redirect的使用〜路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想将用户重定向回位于我的web应用程序的根目录的登录页面的方法。

我用下面的code:

 的Response.Redirect(〜/的Login.aspx ReturnPath这样=?+ Request.Url.ToString());

这不,虽然工作。我的假设是,ASP.NET会自动解析URL到正确的路径。通常情况下,我只想用

 的Response.Redirect(../的Login.aspx ReturnPath这样=?+ Request.Url.ToString());

但这种code是一个母版页,并且可以从任何文件夹级别执行。我该如何解决此问题得到什么?


解决方案

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));

这篇关于Response.Redirect的使用〜路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:00