使用session对用户进行登录验证

先在配置文件里设置好sessionState,例如:

 

  <system.web>
    <sessionState timeout="3600" mode="InProc"></sessionState>
  </system.web>

 

然后定义用户信息实体类

 

 1         public class UserModel
 2         {
 3             /// <summary>
 4             /// 用户id
 5             /// </summary>
 6             public int ID { getset; }
 7             /// <summary>
 8             /// 用户登录名
 9             /// </summary>
10             public string LoginName { getset; }
11             /// <summary>
12             /// 用户密码
13             /// </summary>
14             public string Password { getset; }
15             /// <summary>
16             /// 真实姓名
17             /// </summary>
18             public string RealName { getset; }
19         }

 设置session的方法(需要引入System.Web命名空间)

 

1         public static void SetSession(UserModel model)
2         {
3             HttpContext.Current.Session["USER"] = model;
4         }

获取session的方法

 

 1         public static UserModel GetSession()
 2         {
 3             if (HttpContext.Current.Session["USER"] == null)
 4             {
 5                 return null;
 6             }
 7             else
 8             {
 9                 return (UserModel)HttpContext.Current.Session["USER"];
10             }
11         }

 

在登录页面Login.aspx用户输入用户名和密码后获取用户信息实体类后,伪代码如下:

UserModel model=GetUserModel(用户输入的用户名,用户输入的密码);

if(model != null)

{

    SetSession(model);//设置session,把用户信息存储到Session["USER"]中

}

 

在只有登录用户才能访问的页面的,进行下面的方法判断

 

 1         public static bool CheckLogin(System.Web.UI.Page page)
 2         {
 3             UserModel model = GetSession();//获取session
 4 
 5             if (model == null)
 6             {
 7                 string strfunc = "alert('你尚未登录或者登陆已超时,请重新登录!');self.parent.location='" + _defaultUrl + "';";
 8                 page.ClientScript.RegisterClientScriptBlock(page.GetType(), "tip", strfunc, true);
 9                 return false;
10             }
11             else
12             {
13                 return true;
14             }
15         }

 

posted on 2012-08-31 17:44  明树  阅读(982)  评论(0编辑  收藏  举报