Ibibo Ibibo -4 years ago 264
C# Question

How do I set cookie expiration to session in C#

I Am creating a website when sessions timeout i want to show username and time of the user but i don't know hot to use sessions with cookies
for e.g. username stored in cookies and session when sessions timeout the username must retrive from the cookies

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download