当前位置导航:炫浪网>>网络学院>>网页制作>>ASP.NET教程

防止session失效的最佳效果

  很多时候用到Session都比较厌烦,主要还因为很容易就丢失了!

  解决的方法有:

  1、设置Session时间;

  在Global.ascx文件中的设置时间: Session.Timeout = 600;

  2、放在服务器里:

  web.config中配置 <sessionstate mode="stateServer">后,在服务中启动 asp.net state service (asp.net状态服务)

  除了以上两种方法外,就是Session + Cookies !双重保险。废话不多说,直接看代码就知道了:

  用户登录实例

  public static bool Islogin(string Uname, string Pwd, bool writecookie)

  {

  bool brt = false;

  com.csfqw.passport.API wsLogin = new NT.Data.SqlServer.com.csfqw.passport.API();

  DataSet ds = wsLogin.IsLogin(Uname, Pwd);

  if (ds.Tables[0].Rows.Count > 0)

  {

  DataRow dr = ds.Tables[0].Rows[0];

  System.Web.HttpContext.Current.Session["username"] = dr["username"].ToString();

  brt = true;

  if (writecookie)

  {

  NTCookies cookie = new NTCookies("NetUser");

  cookie.WriteCookie("username", Uname);

  cookie.SetExpires(60);

  cookie.Domain = "csfqw.com";

  cookie.RespnseCookies();

  brt = true;

  }

  }

  return brt;

  }

  用户退出实例

  public static void UserLoginOut()

  {

  //NTCookies cookie = new NTCookies("NetUser");

  //cookie.ClearCookies();

  //HttpContext.Current.Session.Remove("username");

  ///退出用户

  HttpCookie cookie =System.Web.HttpContext.Current.Request.Cookies["NetUser"];

  if (cookie != null && cookie["username"] != null)

  {

  cookie.Expires = DateTime.Now.AddDays(-1.0d);

  cookie.Domain = "csfqw.com";

  System.Web.HttpContext.Current.Response.AppendCookie(cookie);

  }

  ///撤销专家

  HttpCookie expertcookie = System.Web.HttpContext.Current.Request.Cookies["IsExpert"];

  if (expertcookie != null && expertcookie["Expert"] != null)

  {

  expertcookie.Expires = DateTime.Now.AddDays(-1.0d);

  expertcookie.Domain = "csfqw.com";

  System.Web.HttpContext.Current.Response.AppendCookie(expertcookie);

  }

  HttpContext.Current.Session.Remove("username");

  HttpContext.Current.Session.Remove("Expert");

  }

相关内容
赞助商链接