Nonon
Nonon

Reputation: 1

Determining if user is Log-in or Log-out

Good day everyone. I am a 4th yr college student and I am new in asp,I am currently developing a site for my OJT.I have created a login form for my site now I got confused on what to do with this one. I need to identify if the user has been log-in or log-out.. As the user inputted the exact username and password it will go to this line of codes in which will identity if the user has bees signout or not.

       HttpCookie cookie = new HttpCookie("isLog");
       cookie.Value = "1";
       DateTime dtNow = DateTime.Now;
       TimeSpan tsMinute = new TimeSpan(1, 1, 0, 0);
       cookie.Expires = dtNow + tsMinute;
       Response.Cookies.Add(cookie);

        Response.Redirect("manageService.aspx");

And I have this function to determine if the user has been log-in or log-out..

protected Boolean isLog()
{
    //String strCookieName = Request.QueryString["cookie"].ToString();
    //Grab the cookie
    HttpCookie cookie = Request.Cookies["isLog"];
    String tmp = cookie.Value.ToString();
    return (tmp != null);
}

Now, my problem here is that even though I inputted the correct username and password after reloading the page it will still asked for the user name and password(sends me to the login page). I already set a value for the "isLog" cookie but still it return a wrong info. Please enlighten me in this stuff.. Thank you so much..

Any help is highly appreciated,

-nonon

Upvotes: 0

Views: 244

Answers (1)

The_Butcher
The_Butcher

Reputation: 2488

The problem is that when you are getting the value of the cookie

cookie.Value.ToString()

you are ALWAYS getting a string reference back so tmp will NEVER be null.

What you should do is return (tmp == "1")

.Value is a string property (it returns a string )so you don't have to .ToString() it either.

Also be aware that Request.Cookies["COOKIETHATDOESNTEXIST"] will not throw an exception if the cookie doesnt exists. However calling the .Value property on one that doesn't exists will throw an exception.

Try checking for null first or just simply:

HttpCookie cookie = Request.Cookies["isLog"];

bool isLoggedIn = false;
if(cookie != null && cookie.Value == "1")
{
   isLoggedIn = true;
}
return isLoggedIn;

Upvotes: 0

Related Questions