在實際工作中,ASP.NET中的Session的定義和取消有時是分散的,工作群組中的每個人定義Session的時候不一樣,並且名稱有隨意性,所以做了一個Session的統一管理,便於Session的正常化。
代碼如下:
1. 定義介面:只需要實現 ToString()即可。
1 |
//Interface for Session |
2 |
public interface ISession { |
2. Session 類
// ManagerInfo 是Model中的一個類,直接繼承 |
// 將對象放入Session中時,該對象必須是可序列化的 |
public class LoginSession : ManagerInfo , ISession |
public LoginSession(): base() |
public string SessionID { get; set; } |
public override int GetHashCode() |
return SessionID.GetHashCode(); |
public override string ToString() |
if (!string.IsNullOrEmpty(SessionID)) |
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) |
03 |
return GetSessionValue<T>(Common.Const.AppSetting.GlobalSessionName, _propertyName); |
06 |
public static T GetSessionValue<T>(string _sessionName , string _propertyName) |
08 |
T retVal = default(T); |
09 |
string propertyName = _propertyName.ToLower(); |
11 |
if (Convert.ToString(HttpContext.Current.Session[_sessionName]) != "") |
13 |
object SessionObject = (object)HttpContext.Current.Session[_sessionName]; |
15 |
if (SessionObject is ISession) |
17 |
PropertyInfo[] propertyInfos = SessionObject.GetType().GetProperties(); |
19 |
foreach (var pi in propertyInfos) |
21 |
string refName = pi.Name.ToLower(); |
22 |
if (propertyName == refName) |
24 |
retVal = (T)pi.GetValue(SessionObject, null); |
5. 在程式中可以這樣取得Session中某一項的值:
string _tmpstr = Utilities.GetGlobalSessionValue<string>("username"); |
int _tmpint = Utilities.GetGlobalSessionValue<int>("pagesize"); |
Model.Manager = Utilities.GetGlobalSessionValue<Manager>("ManagerDetail");