473,881 Members | 1,704 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

ASP.net cookies not passing data.

BezerkRogue
68 New Member
I am trying to use cookies to manage session states in an ASP.NET application. The states need to persist only while the browser session is open.

My web.config setting is:
<system.web>
<sessionState cookieless="Use Cookies"/>

I have tried using the following code to create the cookies:

Response.Cookie s("FLI").Valu e = cmpFLI

and I have tried:

Dim UID As New HttpCookie("UID ")
UID.Value = txtUserName.Tex t
Response.Cookie s.Add(UID)

I am using the following code to read the cookies:

If (Request.Cookie s("UID") IsNot Nothing) Then
strUser1 = Request.Cookies ("UID").Valu e
End If

It is either not passing the data or not reading it. What am I missing here?
Jan 9 '08 #1
10 2044
Plater
7,872 Recognized Expert Expert
This bit:
<sessionState cookieless="Use Cookies"/>

Is used for the Session object, not for the actual .Cookies collection.
From your description, you should be using the Session object anyway and not the Cookies

That aside, if you reall want cookies, I've had no trouble using a function like this:
Expand|Select|Wrap|Line Numbers
  1. protected void RecordCookie()
  2.     {
  3.         HttpCookie cookie = new HttpCookie("preferences1");
  4.         cookie.Values.Add("PhoneNumber", tbPhoneNumber.Text  );
  5.         cookie.Values.Add("EmailAddress", tbEmailAddress.Text   );
  6.         cookie.Values.Add("Company", tbCompany.Text  );
  7.         //cookie.Values.Add("OrderedBy", tbOrderedBy.Text);
  8.         //Set how long to keep the cookie
  9.         cookie.Expires = DateTime.MaxValue;
  10.         if (Request.Cookies["preferences1"] == null)
  11.         {   
  12.             Response.Cookies.Add(cookie);
  13.         }
  14.         else
  15.         {
  16.             Response.SetCookie(cookie);
  17.         }
  18.     }
  19.  
Jan 9 '08 #2
BezerkRogue
68 New Member
I tried the session object but I have to maintain a variable throughout the site. Since I can't predict the path that the user will take, it is difficult to account for the session item throughout the site.

How does this function code look in vb?
Jan 9 '08 #3
Plater
7,872 Recognized Expert Expert
I tried the session object but I have to maintain a variable throughout the site. Since I can't predict the path that the user will take, it is difficult to account for the session item throughout the site.

How does this function code look in vb?
The Session object maintains a collection of objects for a particular end user through out their use of the site. Clossing the browser, or going idle for 20mins(default time) will empty the data stored in the session object for the given user.
The session object is available to all aspx pages.

If you want to hold objects for all users use a static class (module in vb?)



As for my cookie code, it was pretty much the same as yours
Jan 9 '08 #4
BezerkRogue
68 New Member
I got the code in place but I don't seem to be getting any data passed. Here is what I have for the cookie creation:
Expand|Select|Wrap|Line Numbers
  1.  'Create cookies
  2.         Dim UID As HttpCookie = New HttpCookie("UID")
  3.         UID.Value = txtUserName.Text
  4.         UID.Expires = "1 / 10 / 2008"
  5.         Response.Cookies.Add(UID)
  6.  
  7.         Dim PWD As HttpCookie = New HttpCookie("PWD")
  8.         PWD.Value = txtPassword.Text
  9.         Response.Cookies.Add(PWD)
  10.  
  11.         Response.Redirect("Default.aspx")
  12.  
And this is what I have for reading the cookies:
Expand|Select|Wrap|Line Numbers
  1.  If (Request.Cookies("UID") IsNot Nothing) Then
  2.             ckUID = Request.Cookies("UID").Value
  3.         Else
  4.             Response.Redirect("Invalid.aspx")
  5.         End If
  6.  
  7.         If (Request.Cookies("PWD") IsNot Nothing) Then
  8.             ckPWD = Request.Cookies("PWD").Value
  9.         Else
  10.             Response.Redirect("Invalid.aspx")
  11.         End If
  12.  
Is there anything else that I might be missing?
Jan 10 '08 #5
Plater
7,872 Recognized Expert Expert
I don't think you can add cookies with a response.redire ct()
Since redirect clears out the response and sends a special http header.
Jan 10 '08 #6
BezerkRogue
68 New Member
ok. Would I use Server.Transfer in this case?
Jan 10 '08 #7
Plater
7,872 Recognized Expert Expert
I guess?
Why are you making a cookie for each value though?
You can store multiple name=value pairs in a single cookie.
Jan 10 '08 #8
BezerkRogue
68 New Member
Depending on the function the user is trying to access, I may only need to pull one value. I'm not real saavy on how cookies work code wise so I gravitated to the path of least resistance.
Jan 10 '08 #9
Frinavale
9,735 Recognized Expert Moderator Expert
Depending on the function the user is trying to access, I may only need to pull one value. I'm not real saavy on how cookies work code wise so I gravitated to the path of least resistance.
Why don't you just create a User Class:
Expand|Select|Wrap|Line Numbers
  1. Public Class MySiteUser
  2.      Private _userID
  3.      Private _pwd
  4.      Public Property UserID As String
  5.           Get
  6.                Return _userID
  7.           End Get
  8.           Set(ByVal value As String)
  9.                _userID=value
  10.           End Set
  11.      End Property
  12.      Public Property PWD As String
  13.           Get
  14.                Return _pwd
  15.           End Get
  16.           Set(ByVal value As String)
  17.                _pwd=value
  18.           End Set
  19.      End Property
  20.     Public Function ValidateUser As Boolean
  21.         'If the user is valid pass back true otherwise false
  22.     End Function
  23.     Public Sub New(ByVal name As String, ByVal pwd As String)
  24.         'lalala initialize 
  25.     End Sub
  26. End Class
  27.  
When the user visits your site, create an instance of your user class and store it in session. A Session Identifier Cookie is automatically set for the user to identify their browser with their session. Then you can check the user on any page in your website by checking the user class...

Expand|Select|Wrap|Line Numbers
  1. Private _theUser As MySiteUser
  2.  
  3.  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  4.     _theUser = Session("_theUser")
  5.     If _theUser is Nothing OrElse _theUser.ValidateUser = False
  6.         Response.Redirect("Invalid.aspx")
  7.     End IF
  8. End Sub
  9.  
Of course you're going to have to create this variable and store it in session in your Login Page:
Expand|Select|Wrap|Line Numbers
  1. Private _theUser As MySiteUser
  2.  
  3.  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
  4.     _theUser = Session("_theUser")
  5.     If _theUser is Nothing OrElse _theUser.ValidateUser = False
  6.        _theUser = New MySiteUser(TXT_LoginName.Text, TXT_PWD.Text)
  7.        Session("_theUser") = _theUser
  8.     End IF
  9.     If _theUser.ValidateUser = True Then
  10.         Response.Redirect("WelcomeDefault.aspx")
  11.     Else
  12.         LBL_Error.Text="You have provided invalid crednetials"
  13.     End If
  14. End Sub
  15.  
Of course the examples I've provided by no means provide any security on passwords. You shouldn't be storing passwords anyways...espec ially not in cookies. You should research how password hashes work and how you can use them...

Also, by using sessions instead of cookies stores important user information on your server instead of the client's browser...where they are vulnerable to being stolen, modified... etc.

The User Class can be used to track anything you want....where they've been in the site...what they have already provided on another page....anythin g you want really.

Check out this quick overview of Sessions...I think it'll help you get a better understanding of how to use them.


-Frinny
Jan 10 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

1
3724
by: Jim Mitchell | last post by:
I have one ASPX page that calls another using server transfer as shown below. The problem is that I do not get the cookie in the second page. The value seems to be blank. Any help would be appreciated. Thanks, Jim
1
4193
by: Jim Mitchell | last post by:
I save a cookie in my intro ASP page, but I can not seem to read it from my ASPX page. In ASP.... Response.Cookies("S2")("UserCompanyID")=rs("Level1") In the target ASPX page I have.... Dim Cookie2 As HttpCookie
1
1423
by: Robert Oschler | last post by:
I have two sites, both with valid P3P policies that passed the W3C P3P validator. On one of the sites, Site A, I have a web page that loads a document from Site B in an IFRAME. In this context the web page on Site A is the "originating" document and the web page on Site B is a 3rd-party document (since it's from a different domain). I thought that having a valid P3P policy would make IE6 in the default Medim setting, allow cookies from...
6
2569
by: Tom | last post by:
I know how to create a cookie using the HttpCookie. I know about setting its domain so it can be shared. So I have created a cookie on web site A and set it to expire in 10 minutes. Now I am on web site B, in VS.NET C# and I want to access the cookie created on web site A.
2
2490
by: Scott | last post by:
I would like to have my ASPX page call a function intended to make changes the the current Page.Response.Cookies. I had thought that to allow the function to modify the Cookies, I would have top pass the collection by REFERENCE. But I am getting "A property or indexer may not be passed as an out or ref parameter" Here is a simple example of what I am trying to do...
11
1189
by: Mark | last post by:
We use cookies to maintain some state information about a users session. They are not file based due to the fact that we don't specify a expiration date. They go away when the session ends. I know it's possible to modify a file based cookie. However, what would it take for a hacker that did not have access to our web server to modify the value of a ram based client cookie that we're creating below? I'm not concerned about someone reading...
6
6452
by: Paul | last post by:
Here is a question that should get everyone going. I have an ecommerce site where I need to pass the order_id to every page. So which method is the best practice to pass this variable between pages: Cookies or Session variable or by the HTTP header (either GET querystring or POST form)? I do not like to use sessions because they time out after 20 minutes of inactivity.
5
1554
by: Kevin Blount | last post by:
I've setup a method (C#) that I can call, passing it a cookie name, then a name-value pair. The idea is that as I can't append to a cookie, I read the cookie value, append by name=pair to the end and write it back... which works fine for adding a single name-value pair on a page. The problem is, I want/need to add multiple name-values pairs, the number of which changing between pages (some might have 3, another 8). In my test scripts...
4
1606
by: oopaevah | last post by:
What are the pitfalls of passing a token in the url once a user is logged on so I can remember who they are? I can easily implement this by adding &token=abcdefghijklmnop123 to each internal link on my web pages once the user is logged on. I won't be passing the username or password in the url, just a token that is created when a user logs on. When the server receives the token it maps it back to the account id. This saves the user...
0
9926
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11095
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10716
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10399
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9552
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7108
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4597
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4194
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.