乐闻世界logo
搜索文章和话题

How do I set cookie expiration to " session " in C#?

1个答案

1

In C#, setting the cookie expiration to "session" means that the cookie will automatically expire when the user closes the browser and will not be persistently stored on the user's device. This can be achieved by omitting the Expires property of the cookie. In ASP.NET, you can use the HttpCookie object to create and modify cookies. Below is a specific example illustrating how to do this:

csharp
public void CreateSessionCookie(HttpResponse response, string name, string value) { // Create a new Cookie HttpCookie cookie = new HttpCookie(name, value); // Do not set the Expires property to make the cookie a session cookie // The Expires property defaults to DateTime.MinValue, so explicit setting is not required // Add the cookie to the current response response.Cookies.Add(cookie); }

In this example, we define a method named CreateSessionCookie that accepts three parameters: an HttpResponse object to add the cookie, the cookie's name, and its value. After creating the HttpCookie object, we do not set its Expires property. This means the cookie will expire when the user closes the browser. Finally, we add the cookie to the response by calling response.Cookies.Add.

This approach is commonly used to maintain login sessions, keeping the user logged in as long as the browser is open and requiring re-login once the browser is closed. This is very useful in many scenarios where user privacy and security are important.

2024年8月12日 12:53 回复

你的答案