您的位置:首页 > 编程语言 > ASP

ASP.NET用户登录后跳转到 登录前 的页面 url 跳转

2012-11-23 14:29 597 查看
在一般有用户登录的网站中,都会有需要用户登录后才能操作的页面,如果在用户登录后能跳转到之前的页面,就会给用户一个很好的体验,也能让他们更容易的浏览要操作的页面。这中间主要用到的是获取Url参数,获取后用于跳转。

主要实现步骤:

为了能很好的说明,主要已两个页面为例,order.aspx,login.aspx

1、order.aspx,实现订单页面,主要功能是实现用户在选定商品时提交订单,但用户必须登陆后才能实现提交的功能,这样才知道是哪个买的嘛。。

以代码表示,能更清楚,在加载到order.aspx页面时,判断用户是否登录,这判断用session判断

protected void Page_Load(object sender, EventArgs e)
{
string returnUrl = Request.Url.AbsoluteUri;//获取当前url地址
if (Session["user"] == null)
{
Response.Redirect("/login.aspx?url=" + Server.UrlEncode(returnUrl));
}
else
{
//执行订购操作,该用户已经登录
}

}


上面主要是实现把当前页的url地址传递给登录页面

2、login.aspx 实现用户登录,得到传递过来的Url参数

代码如下:

//登录方法
private bool Login()
{
//用户验证
//...略...

//判断跳转
if (!string.IsNullOrEmpty(Request.QueryString["url"]))
{
//跳转到登录前页面
string returnUrl = Request.QueryString["url"].ToString();
Response.Redirect(Server.UrlDecode(returnUrl));
}
else
{
//登录页面登录的
}
}


只需简单的跳转就可以实现,如果这样类似的操作很多,最好给予封装成方法统一调用

注: 如果在跳转的页面是在虚拟目录下,而不是根站点目录下,设置有些不同,就要进行判断。。。

这样的话 就要进行url虚拟目录判断

/// <summary>
/// 判断url路径 是否为根目录
/// </summary>
/// <returns></returns>
public static string GetRootUrl()
{
string AppPath = "";
HttpContext HttpCurrent = HttpContext.Current;
HttpRequest Req;
if (HttpCurrent != null)
{
Req = HttpCurrent.Request;

string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);

if (Req.ApplicationPath == null || Req.ApplicationPath == "/")
//直接安装在   Web   站点
AppPath = UrlAuthority;
else
//安装在虚拟子目录下
AppPath = UrlAuthority + Req.ApplicationPath;
}
return AppPath;
}


代码注释:Req.Url.GetLeftPart(UriPartial.Authority); 返回http://localhost 在根目录情况下,如果是在虚拟目录下(虚拟目录设置为web)则返回的是http://localhost/web

这样在order.apsx页面中就在执行跳转之前就要加上Req.Url.GetLeftPart(UriPartial.Authority)的返回值

如: string returnUrl =Req.Url.GetLeftPart(UriPartial.Authority)+ Request.Url.AbsoluteUri;//获取当前url地址

这样就能正确的执行跳转了。。。

附:

这里附上Request获取url信息的各种方法比较

以下转自:http://www.cnblogs.com/dudu/archive/2004/02/20/1435.html

测试的url地址是http://www.test.com/testweb/default.aspx, 结果如下:

Request.ApplicationPath: /testweb
Request.CurrentExecutionFilePath: /testweb/default.aspx
Request.FilePath: /testweb/default.aspx
Request.Path: /testweb/default.aspx
Request.PathInfo:
Request.PhysicalApplicationPath: E:/WWW/testweb/
Request.PhysicalPath: E:/WWW/testweb/default.aspx
Request.RawUrl: /testweb/default.aspx
Request.Url.AbsolutePath: /testweb/default.aspx
Request.Url.AbsoluteUri: http://www.test.com/testweb/default.aspx Request.Url.Host: www.test.com
Request.Url.LocalPath: /testweb/default.aspx


综上就为实现登录跳转的基本实现,主要是运用了url参数对跳转前的判断,然后在登录的时候进行获取。。

主要需要了解的是Request.Url的给个不同属性
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐