欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#程序中session的基本设置示例及清除session的方法

程序员文章站 2022-04-28 20:59:10
session的基本设置: using system; using system.collections.generic; using system.te...

session的基本设置:

using system;
using system.collections.generic;
using system.text;
using system.web;
using system.web.sessionstate;

namespace oaframework
{
  public class csession
  {
      public static object get(string key)
    {
      return httpcontext.current.session[key];
    }


  public static string getstring(string key)
    {
      object obj = httpcontext.current.session[key];
      if (obj == null) return "";
      else return obj.tostring();
    }


    public static object get(string key,object defaultvalue)
    {
      if (httpcontext.current.session[key] == null)

        return defaultvalue;
      else
        return httpcontext.current.session[key];

    }


    public static object get(string key, object defaultvalue,boolean canadd)
    {
      if (httpcontext.current.session[key] == null)
      {
        if(canadd==true)
          httpcontext.current.session.add(key, defaultvalue);

        return defaultvalue;
      }
      else
        return httpcontext.current.session[key];

    }


    public static boolean set(string key,object value)
    {
      try
      {
        if (value == null && httpcontext.current.session[key] != null)
        {
          httpcontext.current.session.remove(key);
        }
        else if (httpcontext.current.session[key] == null)
          {
            httpcontext.current.session.add(key, value);
          }
          else
          {
            httpcontext.current.session[key] = value;
          }

        return true;
      }
      catch (exception ex)
      {
        cmsgbox.show(ex.message); 
        return false;
      }

    }
 

      
    
  }
}

清除session:

session.abandon();//清除全部session
//清除某个session
session["username"] = null;
session.remove("username");