asp.net BasePage类+Session通用用户登录权限控制


但是很多人都喜欢在
复制代码 代码如下:

protected void Page_Load(object sender, EventArgs e)
{}

里面来写代码,甚至在某些按钮里面写判断session是否存在~~
这样当然是能实现效果的,问题就在,如果有1000个页面~~你需ctrl+C。。。Ctrl+V 很多次~~~
我的思路就是写一个BasePage类继承 System.Web.UI.Page
复制代码 代码如下:

public class BasePage : System.Web.UI.Page
{
//pageunload事件,并不是指浏览器关闭,而是指页面关闭,所以刷新的时候,依然会执行以下事件
protected void Page_Unload(object sender, EventArgs e)
{
}
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
if (!SessionData.IsLogin())
{//这里写 跳转到登陆页面:例如:
Response.Redirect(string.Format("~/ReLogin.aspx?Page={0}", Request.Path));
}}

为什么我这里要带 Page 参数,就是为了在登录成功以后可以返回到登录前的那一个页面
另外我也贡献一个SessionData类:
复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ExpressPlatform.Common;
namespace ExpressPlatform.Web.AppCode
{
public class SessionKey
{
public const string UserInfo = "user";
}
/// <summary>
/// 所有session中的数据,在该类管理
/// </summary>
public class SessionData
{
/// <summary>
/// 获取session 中的 用户信息
/// </summary>
/// <returns></returns>
public static MdlSessionCustomerInfo GetUserInfo()
{
MdlSessionCustomerInfo userInfo = SessionManager<MdlSessionCustomerInfo>.GetSessionObject(SessionKey.UserInfo);
if (userInfo == null)
{
userInfo = new MdlSessionCustomerInfo();
//把内容储存到应用程序
SessionManager<MdlSessionCustomerInfo>.SetSessionObject(SessionKey.UserInfo, userInfo);
}
return userInfo;
}
/// <summary>
/// 重新设置session 中的用户信息
/// </summary>
/// <param name="userInfo"></param>
public static void SetUserInfo(MdlSessionCustomerInfo userInfo)
{
SessionManager<MdlSessionCustomerInfo>.SetSessionObject(SessionKey.UserInfo, userInfo);
}
/// <summary>
/// 清楚session中用户信息
/// </summary>
public static void ClearUserInfo()
{
SessionManager<MdlSessionCustomerInfo>.SetSessionObject(SessionKey.UserInfo, null);
}
/// <summary>
/// 是否登入
/// </summary>
/// <returns></returns>
public static bool IsLogin()
{
bool ret = false;
MdlSessionCustomerInfo userInfo = SessionManager<MdlSessionCustomerInfo>.GetSessionObject(SessionKey.UserInfo);
if (userInfo != null)
ret = true;
return ret;
}
}
}

复制代码 代码如下:

public class BasePage : System.Web.UI.Page

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3