Basepage类+Session通用用户登录权限控制

SessionManager.cs

1 using System.Web;
2
3  public class SessionManager<T>
4 {
5 public static T GetSessionObject(string key)
6 {
7 object obj = HttpContext.Current.Session[key];
8 if (obj == null)
9 return default(T);
10 else
11 return (T)obj;
12 }
13
14 public static void SetSessionObject(string key, T obj)
15 {
16 HttpContext.Current.Session[key] = obj;
17 }
18 }
19  

SessionData.cs

1 using Models;
2
3  public class SessionKey
4 {
5 public const string UserInfo = "usrelogin";
6 }
7
8  public class SessionDate
9 {
10 /// <summary>
11 /// 获取session中的用户信息
12 /// </summary>
13 /// <returns></returns>
14   public static UserLogin GetUserInfo()
15 {
16 UserLogin userInfo = SessionManager<UserLogin>.GetSessionObject(SessionKey.UserInfo);
17 if (userInfo == null)
18 {
19 userInfo = new UserLogin();
20 //把内容储存到应用程序
21   SessionManager<UserLogin>.SetSessionObject(SessionKey.UserInfo, userInfo);
22 }
23 return userInfo;
24 }
25 /// <summary>
26 /// 重新设置session中的用户信息
27 /// </summary>
28 /// <param name="userInfo"></param>
29   public static void SetUserInfo(UserLogin userInfo)
30 {
31 SessionManager<UserLogin>.SetSessionObject(SessionKey.UserInfo, userInfo);
32 }
33
34 /// <summary>
35 /// 清除session中用户信息
36 /// </summary>
37   public static void ClearUserInfo()
38 {
39 SessionManager<UserLogin>.SetSessionObject(SessionKey.UserInfo, null);
40 }
41
42 /// <summary>
43 /// 是否登录
44 /// </summary>
45 /// <returns></returns>
46   public static bool IsLogin()
47 {
48 bool ret = false;
49 UserLogin userInfo = SessionManager<UserLogin>.GetSessionObject(SessionKey.UserInfo);
50 if (userInfo != null)
51 ret = true;
52 return ret;
53 }
54 }

BasePage.cs

1 using System;
2  using System.Web.UI;
3
4  public class BasePage:Page
5 {
6 protected void Page_Unload(object sender, EventArgs e)
7 {
8
9 }
10
11 protected override void OnPreInit(EventArgs e)
12 {
13 base.OnPreInit(e);
14 if (!SessionData.IsLogin())
15 {
16 Response.Redirect("~/Web/Default.aspx");
17 }
18 }
19 }

UserLogin为实体类。

在页面后台中直接继承BasePage就可以了。

posted @ 2010-09-16 08:41  很久以前我就知道博客园的昵称可以很长很长很长很长  阅读(1548)  评论(0编辑  收藏  举报