Thursday 2 August 2007

Cookies

Yesterday I was going through the concept of cookies, for the first time in terms of applying it in one of my website. I had to store some data, to be more specific-name of the logged person, so that the next page can say Hi to him in a more familiar way. It works fine while going by the intended route i.e. the login page to the next page. It worked fine when I refresh the page. I used the following code to write the cookie

Dim cookiename as new HttpCookie("name")
cookiename.Value=dr("FirstName")+" "+dr("LastName")
cookiename.Expires=DateTime.Now.AddDays(7)
cookiename.Domain="Default3.aspx"
Response.Cookie.Add(cookiename)

Here "name" is the name of the cookie and dr is defined as:
"Dim dr As SqlDataReader"
which I used to access the data from server.
Expire time I kept at 7 days from the last time of logging.
And Domain is the page for which the cookie "name" is intended for.

On the "Default3.aspx" page, I wrote the following code on Page Load to invoke the cookie
Response.Write("Hi Mr. " + Request.Cookies("Name").Value + "")

I started getting problem when redirecting to "Default3.aspx" page from a page other then the login page. I was confused why the cookie can't store the values for 7 days or until I log on as a different user. Whatever the solution may be, at this point of time my Technical Lead suggested me to work on Forms authentication, something which will be more secure compared to cookies (cookies can't be used to store secure information).
Now I jumped to the learning part of forms authentication. Hope, my next blog is going to be on the same topic. Till then....:-)

No comments: