ASP.NET 中的Session统一管理

时间:2022-12-10 21:57:56

在实际工作中,ASP.NET中的Session的定义和取消有时是分散的,工作组中的每个人定义Session的时候不一样,并且名称有随意性,所以做了一个Session的统一管理,便于Session的规范化。

代码如下:

1. 定义接口:只需要实现 ToString()即可。

1 //Interface for Session
2     public interface ISession {
3         string ToString();
4     }

2. Session 类

// ManagerInfo 是Model中的一个类,直接继承
// 将对象放入Session中时,该对象必须是可序列化的
 [Serializable]
 public class LoginSession : ManagerInfo , ISession
 {
     public LoginSession(): base()
     {
         SessionID = "";
     }
 
     public string SessionID { get; set; }
 
     public override int GetHashCode()
     {
         return SessionID.GetHashCode();
     }
 
     public override string ToString()
     {
         if (!string.IsNullOrEmpty(SessionID))
             return SessionID;
         else
             return "";
     }
 }

3. Session赋值

1 LoginSession currentManager = new LoginSession();
2 currentManager.username="Admin";
3 currentManager.permission="all";
4 currentManager.SessionID = HttpContext.Current.Session.SessionID;<br>HttpContext.Current.Session[AppSetting.GlobalSessionName] = currentManager;
5 HttpContext.Current.Session.Timeout = 200;

4. 取得Session的值

01 public static T GetGlobalSessionValue<T>(string _propertyName)
02 {
03     return GetSessionValue<T>(Common.Const.AppSetting.GlobalSessionName, _propertyName);
04 }
05  
06 public static T GetSessionValue<T>(string _sessionName , string _propertyName)
07 {
08     T retVal = default(T);
09     string propertyName = _propertyName.ToLower();
10  
11     if (Convert.ToString(HttpContext.Current.Session[_sessionName]) != "")
12     {
13         object SessionObject = (object)HttpContext.Current.Session[_sessionName];
14  
15         if (SessionObject is ISession)
16         {
17             PropertyInfo[] propertyInfos = SessionObject.GetType().GetProperties();
18  
19             foreach (var pi in propertyInfos)
20             {
21                 string refName = pi.Name.ToLower();
22                 if (propertyName == refName)
23                 {
24                     retVal = (T)pi.GetValue(SessionObject, null);
25                     break;
26                 }
27             }                  
28         }
29     }
30  
31     return retVal;
32 }

5. 在程序中可以这样取得Session中某一项的值:

string _tmpstr = Utilities.GetGlobalSessionValue<string>("username");
int _tmpint = Utilities.GetGlobalSessionValue<int>("pagesize");
Model.Manager = Utilities.GetGlobalSessionValue<Manager>( "ManagerDetail" );