how we create session in login page in asp .net with c# give me full example......
Asked
Active
Viewed 8.1k times
3 Answers
19
Assuming that your code is in the page (either inline or in the code behind) you can just use...
DataType someValue = (DataType)Session["SessionVariableNameHere"]; //Getter
Session["SessionVariableNameHere"] = someNewValue; //Setter
Obviously you'll need to name your session variable properly, and cast to the appropriate data type when you get it back out of the session.
EDIT - A Full Example
protected void Login1_LoggedIn(object sender, EventArgs e)
{
Session["LoginTime"] = DateTime.Now;
}
and later in a page load...
protected void Page_Load(object sender, EventArgs e)
{
Literal1.Text = "Last Online: " + ((DateTime)Session["LoginTime"]).ToString("yyyy-MM-dd");
}

Karl Nicoll
- 16,090
- 3
- 51
- 65
5
When user enters correct username & password. create a session which will hold flag
if(userLoggedInSuccessfully)
{
Session["SessionVariableName"] = "Flag";
}
If you are using master page in your page just check on page_load
page_load()
{
if(Session["SessionVariableName"] != null)
{
if(Session["SessionVariableName"]=="Flag")
{
//Valid User
}
else
{
//Invalid user
}
}
else
{
//Session expired
}
}

Ulhas Tuscano
- 5,502
- 14
- 58
- 89
4
I usually define a (base) page-level property and try to avoid hard-coding the session variable name every time I have to reference it. Here's an example:
In Constants.cs:
public static class Constants
{
public static class SessionKeys
{
public static string MY_SESSION_VARIABLE = "MySessionVariable"; //Or better yet - a newly generated GUID.
}
}
In the page's code-behind, define your property:
protected MyType MyVariable
{
get
{
MyType result = null;
object myVar = Session[Constants.SessionKeys.MY_SESSION_VARIABLE];
if (myVar != null && myVar is MyType)
{
result = myVar as MyType;
}
return result;
}
set
{
Session[Constants.SessionKeys.MY_SESSION_VARIABLE] = value;
}
}
In the page's code-behind, reference the property:
//set
MyVariable = new MyType();
//get
string x = MyVariable.SomeProperty;

Kon
- 27,113
- 11
- 60
- 86