中国设计秀欢迎投稿
中国设计秀设计资源站
平面设计 画册 VI欣赏 包装 CG-插画 搜索 个人网页 Alexa排名 CSS 建站资源 下载专区 JS特效 品牌服装 服装院校 专题欣赏 SEO 图标欣赏 专题
广州网站设计 维美网站建设 域名注册 虚拟主机 广州网站建设 广州网页设计 虚拟主机 域名注册 素材下载 广告服务 中国品牌形象设计 网站推广 家具中国
求创科技
中国设计秀
中国福网
金视觉
中国设计秀欢迎你
中国品牌形象设计网
中国设计秀
当前位置:网络学院首页 >> 编程开发 >> .net >> ASP.NET状态管理

ASP.NET状态管理 (2)

来源:中国设计秀    作者:    点击:256     加入收藏    发表评论
0
顶一下
关键字:状态 管理
中资源

  using System;
  using System.Data;
  using System.Configuration;
  using System.Collections;
  using System.Web;
  using System.Web.Security;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;
  using System.Web.UI.HtmlControls;
  
  namespace ASPNETState
  {
   public partial class Cookie : System.Web.UI.Page
   {
   protected void Page_Load(object sender, EventArgs e)
   {
   if (Request.Cookies["UserName"] != null)  //注意是Request
   {
   Response.Write("亲爱的" + Request.Cookies["UserName"].Value + ",欢迎你光临!");
  
   }
   else
   {
   Response.Write("欢迎光临!");
   }
  
   }
  
   protected void btnZC_Click(object sender, EventArgs e)
   {
   Response.Cookies["UserName"].Value = txtUser.Text;
   Response.Cookies["UserName"].Expires = DateTime.Now.AddSeconds(10); //10秒钟后失效,即Cookies["UserName"]的信息丢失;或者手工删除(IE中选项删除Cookie)
   }
   }
  }
  四、查询字符串
  在讲查询字符串之前先了解一下GET 和 POST方法的不同:
   通过HTTP从Web服务器请求页面或其他资源,有两个通用的方法(GET 和 POST方法)。可使用GET方法直接获得资源,也可使用POST把值传给相应资源。GET方法是缺省的
   假如把一个或多个成对的名称/值附在请求页面的URL后,就变成请求的查询字符串,且在QueryString集合中提供给ASP页面。单击Web页面、Email消息或其它文档的超链接,或在浏览器的地址栏中输入地址并按回车,或单击浏览器中的Links或Favorites按钮,所有这些都要使用GET方法。
   因此,对这些动作中传递值给ASP的唯一方法是通过QueryString集合,把值附在URL后。
   http://mysite.com/process_page.asp?FirstName=Priscilla&LastName=Descartes
   可以采用如下方式访问在QueryString集合中提供的值(QueryString就是下面要讲的查询字符串):
   strFirstName = Request.QueryString("FirstName") ''Return "Priscilla"
   strLastName = Request.QueryString("LastName") ''Return "Descartes"
   strRaw = Request.QueryString
   Return "FirstName=Priscilla&LastName=Descartes"
  在一个页面内使用<FORM>段时,可以设置打开的FORM标记的METHOD属性值为“GET”或“POST”,缺省值为“GET”。假如使用“GET”或省略其属性,浏览器将该值绑定在页面所有控件上,成为一个查询字符串,且附在被请求页面的URL上。当这个请求到达Web服务器时,其值由ASP的Request.QueryString集合提供。然而,假如设置METHOD属性为“POST”,浏览器将值包装进发送服务器的HTTP报头中,通过Request.Form集合提供给ASP。
   通常来说,可以在所有的HTML窗体中使用GET方法。然而,浏览器或服务器的URL字符串长度存在一定的限制。因此,附有长的字符串可能会引起溢出和某些字符串的字符被截掉。同时,查询字符串出现在浏览器的地址栏和所有的保存的链接和收藏夹中。不仅如此,还显露了通过Web服务器时在HTTP请求中不想显示的值,它也可能出现你的服务器和其他路由服务器的日志文件中。在HTTP请求报头中的值很少是可见的,并且不出现在日志文件中。
   使用POST方法需要注意的小问题是,当用户重新下载<FORM>时,窗体的值将不再保留,其值为空且必须重新输入。然而,当附在URL上时,其值被存储为一个链接,将被保留,因此将出现在所有的URL与字符串结合的请求中,这或许是个优点也可能是个缺点,这根据应用而定(一些浏览器在客户端上能够在一定范围内自动保留一个页面上的值)。
  
  先看看get方法(利用查询字符串):
  1、查询字符串提供了一种简单而受限制的维护状态信息的方法,我们可以方便地给那个信息从一个网页传递给另一个网页。
  2、带有查询字符串的URL如下所示:
  http://localhost:1305/QueryString_Show.aspx?username=xieex&password=1111
  3、使用:
  string sUserName,sPwd;
  sUserName = Request.Params["username"].ToString();
  sPwd = Request.Params["password"].ToString();
  或
  sUserName = Request.QueryString["username"].ToString();
  sPwd = Request.QueryString["password"].ToString();
  或
  sUserName = Request["username"].ToString();
  sPwd = Request["password"].ToString();
  都可以取到xieex和1111
  
  其实这样的传值方式很常见也很有用,例如有些系统中,Gird中有很多条数据,我可以对某条数据进行浏览或者编辑,当点“浏览”按钮时,我弹出对话框对该条记录进行浏览,此时不允许编辑,此时我就需要从主页面上传一个状态(state)到对话框页面上来,然后在对话框页面上取其状态(Request["state"].ToString()),此时根据其值(edit或browse)就可以控制是否可以编辑了。
  
  参见实例(QueryString.aspx和QueryString_Show.aspx)
  该例子是说在QueryString.aspx页面上注册用户名和密码,然后跳转到另一个页面上,在另一个页面上取其用户名和密码。
  在该页面上注册用户名和密码
  
  
  using System;
  using System.Data;
  using System.Configuration;
  using System.Collections;
  using System.Web;
  using System.Web.Security;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;
  using System.Web.UI.HtmlControls;
  
  namespace ASPNETState
  {
   public partial class QueryString : System.Web.UI.Page
   {
   protected void Page_Load(object sender, EventArgs e)
   {
  
   }
  
   protected void Button1_Click(object sender, EventArgs e)
   {
   Response.Redirect("QueryString_Show.aspx?username=" + txtUser.Text + "&password=" + txtPwd.Text);
   }
   }
  }
  在另一个页面上取用户名和密码:
  
  using System;
  using System.Data;
  using System.Configuration;
  using System.Collections;
  using System.Web;
  using System.Web.Security;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;
  using System.Web.UI.HtmlControls;
  
  namespace ASPNETState
  {
   public partial class QueryString_Show : System.Web.UI.Page
   {
   protected void Page_Load(object sender, EventArgs e)
   {
   Response.Write("用户:" + Request.Params["username"]+"<br>");
   Response.Write("密码:" + Request.Params["password"]+"<br>");
  
   Response.Write("用户:" + Request.QueryString["username"]+"<br>");//get方法时用Request.QueryString
   Response.Write("密码:" + Request.QueryString["password"]+"<br>");
  
   Response.Write("用户:" + Request["username"]+"<br>");
   Response.Write("密码:" + Request["password"]+"<br>");
   }
   }
  }
  
  
  再看看post方法
  
  直接看例子:(Post.aspx和post_acc.aspx)
  该例子和上面例子差不多,是说在Post.aspx页面上注册用户名和密码,然后跳转到另一个页面上,在另一个页面上取其用户名和密码。
  
  <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Post.aspx.cs" Inherits="ASPNETState.Post" %>
  
  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  
  <html xmlns="http://www.w3.org/1999/xhtml" >
  <head runat="server">
   <title>无标题页</title>
  </head>
  <body>
   <!--注意action="post_acc.aspx" method="post"-->
   <form action="post_acc.aspx" method="post">
   <div>
   用户:<input id="txtUser" type="text" name="username" /><br />
   <br />
   密码:<input id="txtPwd" type="text" name="pwd" /><br />
   <br />
   <input id="Button1" type="submit" value="提交" /></div>
   <!--注意按钮的type为submit-->
   </form>
  </body>
  </html>
  在另一个页面上取用户名和密码:
  
  
  using System;
  using System.Data;
  using System.Configuration;
  using System.Collections;
  using System.Web;
  using System.Web.Security;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;
  using System.Web.UI.HtmlControls;
  
  namespace ASPNETState
  {
   public partial class post_acc : System.Web.UI.Page
   {
   protected void Page_Load(object sender, EventArgs e)
   {
   if (!IsPostBack)
   {
   Response.Write(Server.MapPath("post.aspx"));
  
   Response.Write("用户:" + Request.Form["username"]);//post方法时用Request.Form
   Response.Write("密码:"  + Request.Params["pwd"]);
   }
   }
   }
  }
  第三部分 基于服务器的状态管理
  信息存储在服务器上,尽管其安全型较高,但会占用较多的web服务器资源。服务器端通常用以下方式实现状态管理:
  一、Application对象
  二、Session对象
  
  一、Application状态
  1、应用程序级别的状态存取(就是说服务器上的应用程序,各个客户端都可以访问它)
  2、变量状态的存储和提取
   存储: Application["username"] = "xieex";
   提取: string strUserName = Application["username"];
  3、同时访问要加锁,防止并发冲突
   Application.Lock();
   Application.Unlock();
  Application是保存在服务器内存中的。
  参见实例(ApplicationState.aspx)
  该实例用于记录访问该页面的访问者个数,用Application存储变量,这样不会因为一次会话结束而把访问记录清零。
  
  
  using System;
  using System.Data;
  using System.Configuration;
  using System.Collections;
  using System.Web;
  using System.Web.Security;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;
  using System.Web.UI.HtmlControls;
  
  namespace ASPNETState
  {
   public partial class ApplicationState : System.Web.UI.Page
   {
   protected void Page_Load(object sender, EventArgs e)
   {
   Application.Lock(); //加锁,防止并发,保证同一时间只有一个用户对其访问
   if (Application["count"] != null)
   {
   Application["count"] = (Int32)Application["count"] + 1;
   }
   else
   {
   Application["count"] = 1;
   }
   Application.UnLock();
   Response.Write("您是第"+Application["count"]+"位访问者!");
   //每访问一次都加1,只有当IIS服务重启时才会清零
  
   }
   }
  }
  另一个例子(模拟网站的当前用户人数和访问总人数)
  Global.asax
  
  
  using System;
  using System.Data;
  using System.Configuration;
  using System.Collections;
  using System.Web;
  using System.Web.Security;
  using System.Web.SessionState;
  using System.IO;
  
  namespace ASPNETState
  {
   public class Global : System.Web.HttpApplication
   {
   /**//// <summary>
   /// 必需的设计器变量。
   /// </summary>
   private System.ComponentModel.IContainer components = null;
  
   private FileStream fileStream;
   private StreamReader reader;//读字符流
   private StreamWriter writer;//写字符流
  
   public Global()
   {
   InitializeComponent();
   }
  
   protected void Application_Start(object sender, EventArgs e)
   {
   Application["CurrentGuests"] = 0;//初始花为0;
   fileStream = File.Open(Server.MapPath("counts.text"), FileMode.OpenOrCreate);//文件不存在,创建文件
   reader = new StreamReader(fileStream);//要读取的完整路径
   Application["AllGuests"] = Convert.ToInt32(reader.ReadLine()); //从当前流中读取一行字符并将数据作为字符串返回
   reader.Close();//关闭流
   }
  
   protected void Session_Start(Object sender, EventArgs e)//当用户访问网站时,在线用户+1,总访问数+1
   {
   Application.Lock();//同步,避免同时写入
  
   Application["CurrentGuests"] = (int)Application["CurrentGuests"] + 1;//总在线用户数
   Application["AllGuests"] = (int)Application["AllGuests"] + 1;//访问网站的总用户数
   fileStream = new FileStream(Server.MapPath("counts.text"), FileMode.OpenOrCreate, FileAccess.ReadWrite);//
   writer = new StreamWriter(fileStream);//实现一个写入流,使其以一种特定的编码向流中写入字符
   writer.WriteLine(Application["AllGuests"].ToString());//把访问网站的总用户数再次写入到文件
   writer.Close();//关闭写入流
  
   Application.UnLock();//同步结束
   }
  
   protected void Application_BeginRequest(Object sender, EventArgs e)
   {
  
   }
  
   protected void Application_EndRequest(Object sender, EventArgs e)
   {
  
   }
  
   protected void Application_AuthenticateRequest(Object sender, EventArgs e)
   {
  
   }
  
   protected void Application_Error(Object sender, EventArgs e)
   {
  
   }
  
   protected void Session_End(Object sender, EventArgs e)//当前用户退出网站时,在线用户数量-1,
   {
   Application.Lock();
   Application["CurrentGuests"] = (int)Application["CurrentGuests"] - 1;//总在线用户数量-1
   Application.UnLock();
  
   }
  
   protected void Application_End(Object sender, EventArgs e)
   {
  
   }
  
  
   private void InitializeComponent()
   {
   this.components = new System.ComponentModel.Container();
   }
   }
  }
  在页面上显示,需写代码:
  
  
   protected void Page_Load(object sender, EventArgs e)
   {
   this.Label1.Text = "正在访问站点的用户数:" + Application["CurrentGuests"].ToString();
   this.Label2.Text = "访问过站点的总用户数:" + Application["AllGuests"].ToString();
   }
  Application对象的使用建议:
  1、对于频繁使用(很多用户都要使用的)的数据使用该对象
  2、不要把太多的信息放在该对象中
  3、如果站点有很大的通信量,建议使用Web.Config
  
  
  二、Session状态
  对网站的一次访问叫做会话(Session),超时后,自动结束会话(一般是20分钟),Session也是保存在服务器内存中的。
  使用Session时的情况,如:
  1、购物车:网络用户决定购买的商品列表
  2、用户信息:访问者的姓名
  3、用户设置:个性化界面
  等等
  
  ASP.NET会话状态模块在Web.config文件中像这样配置(不进行额外设置,以下是默认设置)的:
  <sessionState mode="InProc" cookieless="false" timeout="20" />
  mode属性设为InProc(默认值),表明会话状态要由ASP.NET存储在内存中
  cookieless属性设为false,表明不用Cookie来传递会话ID,这就避免了用户禁用了Cookie,Session对象无数据可用。
  timeout属性设为20,表示登录网站后,如果20分钟不对其进行操作,则该会话结束,需要重新登录。
  
  Session属性和方法:
  1、TimeOut属性:
  获取和设置会话结束之前的时间段,以分钟为单位,默认为20分钟
  2、Abandon():
  结束当前会话,会话中的所有信息都被清空
  3、Clear():
  删除当前会话中的所有信息,但不结束会话
  4、IsNewSession:
  如果会话是在用户访问页面时创建的,则这个属性返回true,当会话需要对某些数据进行初始化后才能使用时,就可以使用这个属性
  
  
  参见实例(SessionState.aspx和SessionState_Redirect.aspx)
  该例子是说在SessionState.aspx页面上注册用户名和密码,然后跳转到另一个页面上,在另一个页面上取其用户名和密码。
  在该页面上注册用户名和密码
  
  using System;
  using System.Data;
  using System.Configuration;
  using System.Collections;
  using System.Web;
  using System.Web.Security;
  using System.Web.UI;
  using System.Web.UI.WebControls;
  using System.Web.UI.WebControls.WebParts;
  using System.Web.UI.HtmlControls;
  
  namespace ASPNETState
  {
   public partial class SessionState : System.Web.UI.Page
   {
   protected void Page_Load(object sender, EventArgs e)
   {
  
[1] [2] [3]
热点文章/相关文章
关于我们 | 联系我们 | 网站建设 | 广告服务 | 版权声明 | 免责声明 | 网站公告 | 友情链接 | 留言 | 旧版入口