Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

SessionExtensions.cs

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace Nop.Core.Http.Extensions;

/// 
/// Represents extensions of ISession
/// 
public static class SessionExtensions
{
    /// 
    /// Set value to Session
    /// 
    /// Type of value
    /// Session
    /// Key
    /// Value
    ///  A task that represents the asynchronous operation
    public static async Task SetAsync(this ISession session, string key, T value)
    {
        await LoadAsync(session);
        session.SetString(key, JsonConvert.SerializeObject(value));
    }

    /// 
    /// Get value from session
    /// 
    /// Type of value
    /// Session
    /// Key
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the value
    /// 
    public static async Task GetAsync(this ISession session, string key)
    {
        await LoadAsync(session);
        var value = session.GetString(key);
        return value == null ? default : JsonConvert.DeserializeObject(value);
    }

    /// 
    /// Remove the given key from session if present.
    /// 
    /// Session
    /// Key
    ///  A task that represents the asynchronous operation
    public static async Task RemoveAsync(this ISession session, string key)
    {
        await LoadAsync(session);
        session.Remove(key);
    }

    /// 
    /// Remove all entries from the current session, if any. The session cookie is not removed.
    /// 
    /// Session
    ///  A task that represents the asynchronous operation
    public static async Task ClearAsync(this ISession session)
    {
        await LoadAsync(session);
        session.Clear();
    }

    /// 
    /// Try to async load the session from the data store
    /// 
    /// Session
    /// A task that represents the asynchronous operation
    public static async Task LoadAsync(ISession session)
    {
        try
        {
            await session.LoadAsync();
        }
        catch
        {
            //fallback to synchronous handling
        }
    }
}