asp.net session的原理

session,会话,指的就是用户在浏览某个网站时,从进入网站到浏览器关闭所经过的这段时间,也就是用户浏览这个网站所花费的时间。

A用户和C服务器建立连接时所处的Session同B用户和C服务器建立连接时所处的Session是两个不同的Session。

当一个session第一次被启用时,一个唯一的标识被存储于本地的cookie中。当用户访问web服务器,则被分配一个sessionID,会话结束或超时时自动释放。没有存储类型限制,存储大小只受内存限制。

设置页的代码:

protected void Button1_Click(object sender, EventArgs e)
    {
        Session["txt1"] = (TextBox1.Text == "") ? "空字符串" : TextBox1.Text;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string[] str = TextBox2.Text.Split(',');
        Session["txt2"] = str;
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        Session["cal"] = Calendar1;
    }
    protected void Button4_Click(object sender, EventArgs e)
    {
        Session.Add("txt1", "234345");
    }
    protected void Button5_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default2.aspx");
    }

目标页:

 protected void Page_Load(object sender, EventArgs e)
    {
       if(Session["txt1"]!=null)
       { Label1.Text = Session["txt1"].ToString(); }
        else
       { Label1.Text = "session为null"; }

        if(Session["txt2"]!=null )
        { string[] str = (string[])Session["txt2"];
        for (int i = 0; i < str.Length; i++)
            Label2.Text += str[i] + "
";
        }

        if(Session["cal"]!=null)
        {
            Calendar cal = (Calendar)Session["cal"];
            Label3.Text = cal.SelectedDate.ToShortDateString();
        }

        if (Session["txt1"] != null)
        { Label4.Text = Session["txt1"].ToString(); }
        else
        { Label4.Text = "session为null"; }
    }

添加重名的session后,会将原来的session覆盖。

创建session有两种方式:Session["txt1"]=“xxxx”和Session.Add("txt1", "234345");

在获取session时,返回的是一个object对象,因此要注意显示转换类型。

清除某一个session:session.remove("keyName");

清除所有的session:Session.Abandon();

注意,如果是在按钮中清除session,那么由页面的生命周期可以知道,pageload事件中仍能读取到清除之前的session值,如果想得到清除之后的值,就需要在清除之后,再一次获取页面response.redirect(当前url);

 protected void Button5_Click(object sender, EventArgs e)
    {
        Session["userName"] = TextBox1.Text;
        Response.Redirect("Default2.aspx");
    }

目标页面:

 protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userName"] == null)
            Response.Redirect("Default.aspx");
        else
            Label1.Text += Session["userName"].ToString();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Session.Remove("userName");
        Response.Redirect("Default2.aspx");//这里也可以回到登陆页面
    }
原文地址:https://www.cnblogs.com/jin-/p/4612706.html