簡體   English   中英

更改ASP.NET的會話狀態cookie的到期日期

[英]Changing expiry on ASP.NET's Session State cookie

我正在使用ASP.NET會話狀態來跟蹤我的網站上登錄的用戶。

但是,我遇到的一個問題是,默認情況下,ASP.NET會話cookie在瀏覽器關閉時設置為過期。

http://ahb.me/43e

我已經嘗試使用類似於以下代碼的東西設置我自己的ASP.NET_SessionId cookie並修改cookie的到期時間:

Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddMonths(1);

這些方法都不起作用,它們都設置了具有相同名稱的第二個cookie。

有沒有辦法改變會話cookie的到期日期?

基於Joe的答案中的鏈接,我想出了這種方法:

public void Application_PostRequestHandlerExecute(object sender, EventArgs e)
{
    UpdateSessionCookieExpiration();
}

/// <summary>
/// Updates session cookie's expiry date to be the expiry date of the session.
/// </summary>
/// <remarks>
/// By default, the ASP.NET session cookie doesn't have an expiry date,
/// which means that the cookie gets cleared after the browser is closed (unless the
/// browser is set up to something like "Remember where you left off" setting).
/// By setting the expiry date, we can keep the session cookie even after
/// the browser is closed.
/// </remarks>
private void UpdateSessionCookieExpiration()
{
    var httpContext = HttpContext.Current;
    var sessionState = httpContext?.Session;

    if (sessionState == null) return;

    var sessionStateSection = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
    var sessionCookie = httpContext.Response.Cookies[sessionStateSection?.CookieName ?? "ASP.NET_SessionId"];

    if (sessionCookie == null) return;

    sessionCookie.Expires = DateTime.Now.AddMinutes(sessionState.Timeout);
    sessionCookie.HttpOnly = true;
    sessionCookie.Value = sessionState.SessionID;
}

此代碼可以插入Global.asax.cs

我建議您使用FormsAuthentication來跟蹤登錄用戶。 您可以使用持久性FormsAuthenticationCookie來實現您想要的。

或者,如果您確實想使用會話狀態,請嘗試使用此技術

只是一個猜測:也許編輯web.config中的session.configuration可能會改變cookie過期? 你可以看看這里

我認為嘗試長時間保持會話是錯誤的方法並限制了您的可擴展性。 會話cookie指向由服務器上的IIS維護的特定會話。 通常,您希望在用戶關閉瀏覽器后關閉會話,以便不消耗非活動用戶的所有可用服務器資源。 您希望離開的用戶的會話關閉,並且資源可供新到達的用戶使用。 這就是會話cookie到期的原因。

如果您想在用戶關閉瀏覽器后維護某些用戶狀態,您可以隨時查看“ 個人資料”等內容 或者,如果這是購物車之類的東西,您可以將購物車保存在數據庫中,然后在再次登錄時將其重新連接到用戶。

Tom的回答幾乎對我有用,除了將cookie轉換為變量並設置其屬性。 我必須直接設置對象的屬性,如下所示:

HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Expires = expiryDate;
HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].HttpOnly = true;
HttpContext.Current.Response.Cookies["ASP.NET_SessionId"].Value = sessionState.SessionID;

我仍然將cookie轉換為變量以檢查它是否為null,如果是則返回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM