Ibibo
Ibibo

Reputation: 197

How do I set cookie expiration to session in C#

I am creating a website, and I'm not sure how to use sessions with cookies.

When sessions timeout, I want to show the username and time of the user; for e.g., username stored in cookies and session. When sessions timeout the username must be retrived from the cookies.

Upvotes: 7

Views: 36709

Answers (1)

misha130
misha130

Reputation: 5706

Lets put things in perspective first. A session is the session a user is experiencing when he is using the website. How it works is basically a user starts a session with the web server, the web server then gives it a key of the session and sets a timeout for the session which are stored as a cookie.

Since this process is automatic and you can only configure it in web.config (unless you are asp.net core vNext, which I doubt) with sessionState https://msdn.microsoft.com/en-us/library/h6bb9cz9%28v=vs.80%29.aspx

A normal HttpCookie on another hand is something you set on your Response object and can give it a specific expiration date like this:

HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddMinutes(1);

// Add the cookie.
Response.Cookies.Add(myCookie);

Which suits your needs more likely.

If you want more information about sessions expiration I'd also suggest you check out http://www.hanselman.com/blog/TroubleshootingExpiredASPNETSessionStateAndYourOptions.aspx

Upvotes: 16

Related Questions