Session with ASP.NET(C#)

if you are new with session, you are in the right place. Here, I will try to put together some code snippets to show various uses of Session. Let’s start with how to assign a Integer value in Session followed by how to retrieve it.

// Assign "userCode" variable to Session  
int userCode = 7;
Session.Add("UserCode", userCode);

//Retrieve "userCode" from Session
int userCode;
userCode= (int)Session["UserCode"];

However, you can assign Object in Session and can retrieve it as well.

User userObject = new User();
userObject.UserName = userNameTextBox.Text;
userObject.UserPassword = passwordTextBox.Text;

User userObjectVerified = new User();
UserManager userManagerObject = new UserManager();

 userObjectVerified = userManagerObject.IsUserAuthenticated(userObject);

 if (userObjectVerified.IsUserAuthenticate == true)
  //Assign User Object in Session
  Session.Add("user", userObjectVerified);
  //login failed 
  loginFailedLabel.Text = "Login Failed.";
catch (Exception loginException)
 loginFailedLabel.Text = loginException.Message.ToString();

//Retrieve User Object from Session
User authorizedUser = null;
authorizedUser = (User)Session["user"];

Finally, you can use this code snippet to check out Session Status.

if (Session.IsNewSession)
 Response.Write("alert('Session Expired/ You are not auhtorized');");

A Rahim Khan


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: