asp.net状态保持相关知识总结

注意网站与项目的区别
    多了命名空间 预编译
编码格式已响应报文为主 response.Charset="gb2312";

无状态(对象销毁 连接断开)
///////////////////////////////
viewstate 客户端 使用 一个页面使用 隐藏域自动保存值 有run="server"
禁用viewstate状态(位置可以选择 页头page指令夹为全部) EnableViewState=“false” 可以用()工具进行状态检测
保存非单值元素 非表单元素状态
 ViewState["num"] = num;(保存值)
 ----图片的序列和反序列化
 ----using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
--- //定义一个变量向页面传值
        protected string str="" ;
        //页面加载
        protected void Page_Load(object sender, EventArgs e)
        {
            //首次加载
            if (!IsPostBack)
            {
                //图片保存到隐藏域中调用序列化方法
                str = ImgToString();
            }
            //提交时
            else
            {
                string s = Request.Form["hd"];
                //调用反序列化方法形成图片
                System.Drawing.Image img = StrToImg(s);
                Response.ContentType = "image/jpeg";
                //保存图片
                img.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }

        private System.Drawing.Image StrToImg(string s)
        {
            //base64解码
            byte[] buffer = Convert.FromBase64String(s);
            //反序列化
            using (MemoryStream ms = new MemoryStream(buffer))
            {
                BinaryFormatter bf = new BinaryFormatter();
                System.Drawing.Image img = bf.Deserialize(ms) as System.Drawing.Image;
                return img;
            }
        }

        private string ImgToString()
        {
            //获取对象的路径
            string path = Request.MapPath("img/IMG_4692.jpg");
            //创建图片
            System.Drawing.Image img = System.Drawing.Image.FromFile(path);
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter bf = new BinaryFormatter();
                //把图片转化为流
                bf.Serialize(ms, img);
                //序列化后的对象 写入字节数组
                byte[] buffer = ms.ToArray();
                //把字节数组,base64编码转换成字符串
                return Convert.ToBase64String(buffer);
            }
        }
------------------------------------------------------------------------------------
cookie也是保存客户端 和域名相关 和浏览器相关 数据最好加密
    把少量数据保存在客户端的内存或硬盘并读取出来的一种技术  cookie位置C:useradmincookie
    存在硬盘时会设置cookie的时间 反之在内存上
    1、普通get请求无cookie 可以通过监视观察报文
    2、服务器通过响应报文头里的set-cookie向浏览器设置cookie信息
    3、浏览器通过请求报文里头的cookie传递浏览器存储的cookie信息
    常用于登录和保存最近浏览的商品 cookie.Expires=datetime.now.addminutes(5) 设置cookie的保存时间
    1、cookie的读写
    //在内存中创建对象
     HttpCookie hc = new HttpCookie("test");
            hc.Value = DateTime.Now.ToString();
            //设置过期时间
            hc.Expires = DateTime.Now.AddDays(5);
            //输出 (并没有真正输出)
            Response.Cookies.Add(hc);
            //读cookie
            HttpCookie hc=Request.Cookies["test"];
            if (hc != null)
            {
                Response.Write(hc.Value);
            }
    2、cookie的删除
            context.Response.ContentType = "text/plain";
            //所有的cookie
            int count = context.Request.Cookies.Count;
            //遍历cookie
            for (int i = 0; i < count; i++)
            {
                HttpCookie hc=context.Request.Cookies[i];
                //设置过期
                hc.Expires = DateTime.Now.AddDays(-1);
                context.Response.Cookies.Add(hc);
            }
            //页面跳转
            context.Response.Redirect("Login.aspx");
        }
        页面登录使用cookie
        <登陆页>if (IsPostBack)
            {
            //接收传值
                string name = Request.Form["txtName"];
                string pwd = Request.Form["txtPwd"];
                //判断
                if (name == "user" && pwd == "user")
                {
                    //创建cookie对象
                    HttpCookie hc = new HttpCookie("name");
                    hc.Value = name;//赋值 设置销毁时间
                    hc.Expires = DateTime.Now.AddDays(7);
                    //添加到集合
                    Response.Cookies.Add(hc);
                    //页面跳转
                    Response.Redirect("06-LoginOver.aspx");
                }
            }
            else
            {
                //页面第一次加载
                if (Request.Cookies["name"] != null)
                {
                    s = Request.Cookies["name"].Value;
                }
            }
        <登陆跳转页>
        if (Request.Cookies["test"] != null)
            {
                Response.Write("欢迎" + Request.Cookies["test"].Value.ToString());
            }
        问题: 输出同名cookie浏览器会重新赋值 反之添加
        设置cookie的路径hc.Path="/文件"(根目录下的文件)
        cookie.Domain(域/域名)
------------------------------------------------------------------------------------
session服务端保存客户端的数据
        在一般处理程序中必须实现接口IRequiresSessionState 添加system.web.sessionstate空间
        session["name"]="";赋值  string str=session["name"].tostring();取值
        销毁session.Abandon(); 对象并没有从池里销毁  Session.Clear();清空对象里的键值对
        页面登录使用session  sessionId 用cookie保存在浏览器的缓存内了
        <页面登录>
        //点击提交
            if (IsPostBack)
            {
                string code = Request.Form["txtCode"].ToLower();
                //判断验证码是否正确
                //因为session有过期机制,所以先判断是否为null
                if (Session["code"] !=null && code == Session["code"].ToString().ToLower())
                {
                    //当验证码正确,移除
                    Session.Remove("code");

                    string name = Request.Form["txtName"];
                    string pwd = Request.Form["txtPwd"];
                    if (name == "admin" && pwd == "admin")
                    {
                        //记录登录成功的状态
                        Session["user"] = name;
                        Response.Redirect("08-LoginOver.aspx");
                    }
                }
                else
                {
                    Response.Write("验证码错误");
                }
            }
        <登陆跳转页>
             //判断是否登录
            if (Session["user"] == null)
            {
             
               
                Response.Write("<script>alert('请登录');location.href='08-Login.aspx'</script>");
            }
            else
            {
                Response.Write(Session.SessionID);
                Response.Write("欢迎"+Session["user"].ToString());
            }
-------验证码
    <%@ WebHandler Language="C#" class="ValidateCode" %>

using System;
using System.Web;
using System.Drawing;
using System.Web.SessionState;
public class ValidateCode : IHttpHandler,IRequiresSessionState {

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "image/jpeg";

        string code = GetRndStr();
        //保存在session上
        context.Session["code"] = code;
        using (Bitmap img = CreateImages(code, "ch"))
        {
            img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    /// <summary>
    /// 数字随机数
    /// </summary>
    /// <returns></returns>
    private string GetRndNum()
    {
        string code = string.Empty;
        Random random = new Random();
        for (int i = 0; i < 4; i++)
        {
            code += random.Next(9);
        }
        return code;
    }
    /// <summary>
    ///  英文随机
    /// </summary>
    /// <returns></returns>
    private string GetRndStr()
    {
        string Vchar = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
        string[] VcArray = Vchar.Split(',');
        string checkCode = string.Empty;
        Random rand = new Random();
        for (int i = 0; i < 4; i++)
        {
            int t = rand.Next(VcArray.Length);
            checkCode += VcArray[t];
        }
        return checkCode;
    }
    /// <summary>
    /// 中文随机
    /// </summary>
    /// <returns></returns>
    private string GetRndCh()
    {
        System.Text.Encoding gb = System.Text.Encoding.Default;//获取GB2312编码页(表)
        object[] bytes = CreateRegionCode(4);//生4个随机中文汉字编码
        string[] str = new string[4];
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        for (int i = 0; i < 4; i++)
        {
            //根据汉字编码的字节数组解码出中文汉字
            str[i] = gb.GetString((byte[])Convert.ChangeType(bytes[i], typeof(byte[])));
            sb.Append(str[i].ToString());
        }
        return sb.ToString();
    }
    /// <summary>
    /// 产生随机中文字符
    /// </summary>
    /// <param name="strlength"></param>
    /// <returns></returns>
    private static object[] CreateRegionCode(int strlength)
    {
        //定义一个字符串数组储存汉字编码的组成元素
        string[] rBase = new String[16] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
        Random rnd = new Random();
        object[] bytes = new object[strlength];

        for (int i = 0; i < strlength; i++)
        {
            //区位码第1位
            int r1 = rnd.Next(11, 14);
            string str_r1 = rBase[r1].Trim();
            //区位码第2位
            rnd = new Random(r1 * unchecked((int)DateTime.Now.Ticks) + i);
            int r2;
            if (r1 == 13)
            {
                r2 = rnd.Next(0, 7);
            }
            else
            {
                r2 = rnd.Next(0, 16);
            }
            string str_r2 = rBase[r2].Trim();

            //区位码第3位
            rnd = new Random(r2 * unchecked((int)DateTime.Now.Ticks) + i);//更换随机种子
            int r3 = rnd.Next(10, 16);
            string str_r3 = rBase[r3].Trim();

            //区位码第4位
            rnd = new Random(r3 * unchecked((int)DateTime.Now.Ticks) + i);
            int r4;
            if (r3 == 10)
            {
                r4 = rnd.Next(1, 16);
            }
            else if (r3 == 15)
            {
                r4 = rnd.Next(0, 15);
            }
            else
            {
                r4 = rnd.Next(0, 16);
            }
            string str_r4 = rBase[r4].Trim();
            //定义两个字节变量存储产生的随机汉字区位码
            byte byte1 = Convert.ToByte(str_r1 + str_r2, 16);
            byte byte2 = Convert.ToByte(str_r3 + str_r4, 16);

            //将两个字节变量存储在字节数组中
            byte[] str_r = new byte[] { byte1, byte2 };

            //将产生的一个汉字的字节数组放入object数组中
            bytes.SetValue(str_r, i);
        }
        return bytes;
    }
    /// <summary>
    /// 画图片的背景图+干扰线
    /// </summary>
    /// <param name="checkCode"></param>
    /// <returns></returns>
    private Bitmap CreateImages(string checkCode, string type)
    {
        int step = 0;
        if (type == "ch")
        {
            step = 5;//中文字符,边界值做大
        }
        int iwidth = (int)(checkCode.Length * (13 + step));
        System.Drawing.Bitmap image = new System.Drawing.Bitmap(iwidth, 22);
        Graphics g = Graphics.FromImage(image);
        g.Clear(Color.White);//清除背景色
        Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };//定义随机颜色
        string[] font = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial", "宋体" };
        Random rand = new Random();

        for (int i = 0; i < 50; i++)
        {
            int x1 = rand.Next(image.Width);
            int x2 = rand.Next(image.Width);
            int y1 = rand.Next(image.Height);
            int y2 = rand.Next(image.Height);
            g.DrawLine(new Pen(Color.LightGray, 1), x1, y1, x2, y2);//根据坐标画线
        }

        for (int i = 0; i < checkCode.Length; i++)
        {
            int cindex = rand.Next(7);
            int findex = rand.Next(5);

            Font f = new System.Drawing.Font(font[findex], 10, System.Drawing.FontStyle.Bold);
            Brush b = new System.Drawing.SolidBrush(c[cindex]);
            int ii = 4;
            if ((i + 1) % 2 == 0)
            {
                ii = 2;
            }
            g.DrawString(checkCode.Substring(i, 1), f, b, 3 + (i * (12 + step)), ii);

        }
        g.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);
        System.IO.MemoryStream ms = new System.IO.MemoryStream();
        return image;
    }
<img onclick="this.src='ValidateCode.ashx?_='+Math.random()" title="看不清?" style="cursor:pointer" src="ValidateCode.ashx" /><input type="text" name="txtCode" /><br />
onclick="this.src='ValidateCode.ashx?_='+Math.random()"鼠标点击随机生成
------------------------------------------------------------------------------------
application服务端保存共享数据
        应用--当前在线人数
        session时间设定 <sessionState timeout="1"></sessionState>web.config
        新建一个全局处理程序
         protected void Application_Start(object sender, EventArgs e)
        {
            Application.Lock();
            Application["count"] = 0;
            Application.UnLock();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Application.Lock();
            Application["count"] = Convert.ToInt32(Application["count"]) + 1;
            Application.UnLock();
        }

        protected void Application_BeginRequest(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)
        {
            Application.Lock();
            Application["count"] = Convert.ToInt32(Application["count"]) - 1;
            Application.UnLock();
        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

原文地址:https://www.cnblogs.com/eric-gms/p/3464885.html