Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 587
Ibibo Avatar asked Jun 07 '16 07:06

Ibibo


1 Answers

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

like image 86
misha130 Avatar answered Oct 31 '22 16:10

misha130