C#,添加,获取,清除Session

class SessionHelper
{//转载请保留原创地址 http://www.luofenming.com/show.aspx?id=ART2019082700002
    /// <summary>
    /// 根据Session名获取Session对象
    /// </summary>
    /// <param name="name"></param>
    /// <returns></returns>
    public static object GetSession(string name)
    {
        return HttpContext.Current.Session[name];
    }

    /// <summary>
    /// 设置Session(添加和修改Session)
    /// </summary>
    /// <param name="name">Session 名</param>
    /// <param name="val">Session 值</param>
    /// <param name="iExpires">调动有效期(分钟) 默认为0,0为不测试有效期</param>
    public static void SetSession(string name, object val, int iExpires = 0)
    {
        HttpContext.Current.Session[name] = val;
        if (iExpires != 0)
        {
            HttpContext.Current.Session.Timeout = iExpires;
        }
    }

    /// <summary>
    /// 清空所有的Session
    /// </summary>
    /// <returns></returns>
    public static void ClearSession()
    {
        HttpContext.Current.Session.Clear();
    }

    /// <summary>
    /// 删除一个指定的Session
    /// </summary>
    /// <param name="name">Session名称</param>
    /// <returns></returns>
    public static void RemoveSession(string name)
    {
        HttpContext.Current.Session.Remove(name);
    }

    /// <summary>
    /// 删除所有的Session
    /// </summary>
    /// <returns></returns>
    public static void RemoveAllSession()
    {
        HttpContext.Current.Session.RemoveAll();
    }
}

评论