简体   繁体   中英

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 eg, username stored in cookies and session. When sessions timeout the username must be retrived from the cookies.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM