5

how we create session in login page in asp .net with c# give me full example......

0

3 Answers 3

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");
}
Sign up to request clarification or add additional context in comments.

Comments

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
                 }

}

Comments

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.