.NET WEBAPP中的Session

来源:互联网 发布:沃尔沃xc60轮毂数据 编辑:程序博客网 时间:2024/05/21 10:26

初学,写个小程序,数据库用ACCESS,后台是C#,ACTION全部用ASHX文件,前台用EXTJS,采用SESSION方法判断用户是否登录

用户登录时在SESSION中写入数据

context.Session["UserName"] = context.Request.Form["loginname"];

//数据库表中每条记录都有ROLEID,取数据时判断如select * from table where roleid=roleid
context.Session["RoleId"] = currole.ID;

//在主要的页面上作用户是否登录判断

context.Session["isLogin"] = true;

用户注销时将这些记录清空

由于老是要取且判断SESSION内容,于是写了个类来处理Session的内容,注意第一个方法最好用

/// <summary>
    /// 此类只包括静态函数,专门读取SESSION的内容
    /// </summary>
    public class SessionItems:IRequiresSessionState
    {
        public static object GetSessionObj(string SessionName)
        {
            if (HttpContext.Current.Session[SessionName] != null)
            {
                return HttpContext.Current.Session[SessionName];
            }
            return null;
        }
        public static string getSessionUserName()
        {
            if (HttpContext.Current.Session["UserName"] != null)
            {
                return (Convert.ToString(HttpContext.Current.Session["UserName"]));
            }            
            return null;
        }
        public static int getSessionRoleID()
        {
            if (HttpContext.Current.Session["RoleId"] != null)
            {
                return (Convert.ToInt32(HttpContext.Current.Session["RoleId"]));
            }    
            return 0;
        }
        public static bool getSessionIsLogin()
        {
            if (HttpContext.Current.Session["isLogin"] != null)
            {
                return (Convert.ToBoolean(HttpContext.Current.Session["isLogin"]));
            }    
            return false;
        }
    }

在ASHX中直接调用SessionItem类的静态方法

注意不管在哪个类中调用,那个类必须实现接口IRequiresSessionState,同时添加using System.Web.SessionState;


原创粉丝点击