In my actual work, ASP. the definitions and cancellation of sessions in NET are sometimes scattered. When everyone in the Working Group defines sessions differently and the names are random, a Session is managed in a unified manner to facilitate the standardization of sessions.
The Code is as follows:
1. Define the interface: you only need to implement ToString.
View sourceprint? 1 // Interface for Session
2 public interface ISession {
3 string ToString ();
4}
2. Session
View sourceprint? // ManagerInfo is a class in the Model and inherits directly
// When an object is put into the Session, the object must be serializable.
[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 assignment
View sourceprint? 1 LoginSession currentManager = new LoginSession ();
2 currentManager. username = "Admin ";
3 currentManager. permission = "all ";
4 currentManager. SessionID = HttpContext. Current. Session. SessionID; <BR> HttpContext. Current. Session [deleetting. GlobalSessionName] = currentManager;
5 HttpContext. Current. Session. Timeout = 200;
4. Get the Session Value
View sourceprint? 01 public static T GetGlobalSessionValue <T> (string _ propertyName)
02 {
03 return GetSessionValue <T> (Common. Const. deleetting. 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. You can obtain the value of a Session in the program as follows:
View sourceprint? String _ tmpstr = Utilities. GetGlobalSessionValue <string> ("username ");
Int _ tmpint = Utilities. GetGlobalSessionValue <int> ("pagesize ");
Model. Manager = Utilities. GetGlobalSessionValue <Manager> ("ManagerDetail ");