Reputation: 67
how we create session in login page in asp .net with c# give me full example......
Upvotes: 5
Views: 82121
Reputation: 16419
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");
}
Upvotes: 19
Reputation: 27441
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;
Upvotes: 4
Reputation: 5620
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
}
}
Upvotes: 5