0

I have a login form with two boxes and button on buttonclick I validate user using sql database and store the id in session and set up FormsAuthentication for later use. on logout button I redirect them logout.aspx where i destroy the session and redirect to login page :

 Session.Abandon();
 FormsAuthentication.SignOut();

now after logout if i go back using browser back button, I still can see my previouse page but if I refresh I get object reference not set to an instance of an object.

protected void Page_Load(object sender, EventArgs e)
Line 33:         {
Line 34:             string id = Session["ID"].ToString();

What is the best work around for this to send user back to login if this happens?

Zaki
  • 5,540
  • 7
  • 54
  • 91

2 Answers2

5

Nota : i suggest you to use

if(Session["ID"] != null)
{

}

But also I suggest you to use this configuration

<system.web>
  <authentication mode="Forms">
    <forms loginUrl="Login.aspx"
           defaultUrl="default.aspx" />
  </authentication>
</system.web>

Your logout link/button should point to a page containing this code, along with whatever else you want.

private void Page_Load(object sender, System.EventArgs e)
{
    // Put user code to initialize the page here
    Session.Abandon();
    FormsAuthentication.SignOut();
}

Nota : sequence diagram

enter image description here

Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
1

You should first check if the Session["ID"] != null Otherwise the user is not authenticated.

But if you use FormsAuthentication you can also use User.Identity.IsAuthenticated

David
  • 435
  • 4
  • 8