In 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.
1 |
//Interface for Session |
2 |
public interface ISession { |
2. Session
// Managerinfo is a class in the model and inherits directly |
// When an object is put into the session, the object must be serializable. |
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 assignment
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. Get the session Value
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. You can obtain the value of a session in the program as follows:
string _tmpstr = Utilities.GetGlobalSessionValue< string >( "username" ); |
int _tmpint = Utilities.GetGlobalSessionValue< int >( "pagesize" ); |
Model.Manager = Utilities.GetGlobalSessionValue<Manager>(
"ManagerDetail"
);