ASP.NET -- WebForm -- Session的使用

ASP.NET -- WebForm --  Session的使用

Session是服务器端状态保持机制。

1. Test4.aspx文件与Test4.aspx.cs文件

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test4.aspx.cs" Inherits="Test4" %>

<!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>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="Button1" runat="server" Text="获取Session的值" onclick="Button1_Click" />
        <asp:Button ID="Button2" runat="server" Text="设置Sessions" onclick="Button2_Click" />
    </div>
    </form>
</body>
</html>
View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test4 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (Session["UserName"]!=null)
        {
            Response.Write(Session["UserName"]);
        }
        else
        {
            Response.Write("Session中没有UserName的值");
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Session["UserName"] = "TestUser";
    }
}
View Code

 

2. 服务器在内存中存储Session数据时,服务器会开辟Session的存储区域,这个区域再分相应的存储单元,并且每个单元加上一个编号,这个编号叫SessionID。

  SessionID以cookie的形式返回给浏览器。Session默认的过期时间是20分钟。

 

再次访问页面时,浏览器会将SessionID通过请求报文发送给服务器端。

 

 

3. 由于Session数据是存储在服务器的内存中的,不要赋值太大的数据,防止占用内存过大。

 

posted on 2018-11-21 09:16  在代码的世界里游走  阅读(783)  评论(0编辑  收藏  举报