views:

207

answers:

3

I want to use session object in my web app.I want to store some cookies too(Some custom informations) .How can i use both without the URL not being modified like http://www.example.com/(S(lit3py55t21z5v55vlm25s55))/orderform.aspx

In my ASP.NET page, I am setting some session variable

Session["customerId"]="Some name";

Then i am trying to set some value in cookie

        HttpCookie objCookie = new HttpCookie("vendorName");
        Response.Cookies.Clear();
        Response.Cookies.Add(objCookie);
        objCookie.Values.Add(cookiename, "ATT");
        DateTime dtExpiry = DateTime.Now.AddDays(2);
        Response.Cookies[cookiename].Expires = dtExpiry;

In this page now i can access the sesion variable values,But when i m being Redirected to another asp.net page, I am not getting my session values there.Its seems like Its being lossed.

Any idea how to solve this. I want both session and cookies

+3  A: 

Cookies and Session variables are independent of each other. You may be confused because by default Asp.Net Sessions use a cookie to store the session identifier and when cookies are disabled, Asp.Net puts the session identifier in a query string value which is visible in the URL.

To use cookies do this

// Set the value in a response
Response.Cookies["SomeCookieVar"].Value = "SomethingImportant";

// After a post back read the value from the request
Request.Cookies["SomeCookieVar"].Value;

Session variables are accessed like this

// Set the value
Session["SomeSessionVar"] = "SomethingElse";
// Read the value
String SomeSetting = Session["SomeSessionVar"];

This is assuming that you are working in C# inside and ASPX page class. VB.Net has slightly different syntax and http handlers and modules require you to do some work to get to Request, Response and Session.

Both Session variables and Cookies values can be mixed and matched to your hearts content without any conflicts. One common scenario is to store values in cookies that you want to persist acrosss different sessions. But in order for that to work, you must set an expiration on your cookie. Cookies without expirations are non-persistent and will not last between browser sessions.

// make the cookie to last for a week
Request.Cookies["SomeCookieVar"].Expiration = DateTime.Now().AddDays(7);
Mark Arnott
+1  A: 

I think your problem may be this

Response.Cookies.Clear(); 

If you clear all the cookies, you will be clearing the cookie that ASP.Net uses to store the session identifier. Without that cookie ASP.Net can't hook up the users Session with subsequent requests and so the Session will be lost.

Mark Arnott
A: 

You might consider using this little library:

http://www.codeproject.com/KB/aspnet/Univar.aspx

It can automatically switch to the session whenever the cookie is unavailable. It also has a server side implementation of the cookie whereby all cookies are stored on the server and asp.net authentification can be used to identify the user.

Ziad