To have different session timeout for different users

I am trying to build a extension method to having variable value to session timeout. The scenario is , I need different session timeout value based on some condition. Here I am using simple username and password matching for authentication, no identity class.
Below is what I tried as an extension method,

    public static class SessionExtensions
{
    public static void SetString(this ISession session,
    string key,
    string value,
    TimeSpan expireAfter)
    {
        lock (session)
        {
            session.SetString(key, value);
        }

        Task.Delay(expireAfter).ContinueWith((task) =>
        {
            lock (session)
            {
                session.Remove(key);
                session.Clear();
            }
        });
    }
}

I created an extension method on ISession where I supply key, value and timeout value,

I use it as below

HttpContext.Session.SetString("SampleKey", "SampleValue", TimeSpan.FromMinutes(5));

This should expire after 5 minutes. It is setting the session also when session.Remove(key) gets called , it show that particular key removed from session. But when I execute some other method in application than HttpContext.Session.GetString(“SampleKey”) retrive value.

I tried both session.remove(key) & session.clear() but its not removing session.

Is there anything missed out in this extension method or I created it on wrong type ?

This is .net 8.0

Earlier we used to do it as demo’d in this question:
Different session time out for different users

But this is not working in .net core or .net 8.0

According to this document, you could find asp.net core’s session is totally different than asp.net, since the asp.net core is using cookie with the session and the asp.net is using cookieless session.

Details, you could check the document’s notice: There is no replacement for the cookieless session feature from the ASP.NET Framework because it’s considered insecure and can lead to session fixation attacks.

Due to this, you couldn’t set the session timeout per user(request), since the session is managed by the cookie and the session cookie is managed by the browser.

Details, you could check below behaviors:

  • The session cookie is specific to the browser. Sessions aren’t shared across browsers.
  • Session cookies are deleted when the browser session ends.
  • If a cookie is received for an expired session, a new session is created that uses the same session cookie.
  • Empty sessions aren’t retained. The session must have at least one value set to persist the session across requests. When a session isn’t retained, a new session ID is generated for each new request.
  • -The app retains a session for a limited time after the last request. The app either sets the session timeout or uses the default value of 20 minutes. Session state is ideal for storing user data:
    That’s specific to a particular session.
  • Where the data doesn’t require permanent storage across sessions.
  • Session data is deleted either when the ISession.Clear implementation is called or when the session expires.
  • There’s no default mechanism to inform app code that a client browser has been closed or when the session cookie is deleted or expired on the client.
  • Session state cookies aren’t marked essential by default. Session state isn’t functional unless tracking is permitted by the site visitor.

One workaround for this is, you could set a custom expire time per session inside the memory cache when you create it.

The memory cache contains the AbsoluteExpirationRelativeToNow property which will expire after the expire time.

Then you could create a custom get session method which will check this cache is exits or not .

Codes like below:

public static class SessionExtensions
{
    private static readonly IMemoryCache Cache = new MemoryCache(new MemoryCacheOptions());

    public static void SetStringWithTimeout(this ISession session, string key, string value, TimeSpan expireAfter)
    {
        session.SetString(key, value);

         var cacheKey = $"{session.Id}";

         Cache.Set(cacheKey, key, new MemoryCacheEntryOptions
        {
            AbsoluteExpirationRelativeToNow = expireAfter
        });
    }

    public static string GetStringWithTimeout(this ISession session, string key)
    {
        var cacheKey = $"{session.Id}";

        // Check if the cache still has the key. If expired, remove it from the session.
        if (!Cache.TryGetValue(cacheKey, out _))
        {
            session.Clear();
            // you return other value to make other logic inside it
            return null;
        }

         return session.GetString(key);
    }
}

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật