cookie的常用操作

cookie介绍: cookie的简单介绍就是把用户的登录信息缓存在本机的浏览器中,且最大容量为4KB,但是这种存储是不安全的,通常一般会进行加密处理,但是依旧不能做到安全,所以一般要优先考虑网站的安全性以及应用场景。

aspx前端代码:

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="CZBK.ItcastProject.WebApp._2015_5_31.Login" %>
 2 
 3 <!DOCTYPE html>
 4 
 5 <html xmlns="http://www.w3.org/1999/xhtml">
 6 <head runat="server">
 7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
 8     <title></title>
 9 </head>
10 <body>
11     <form id="form1" runat="server">
12     <div>
13     用户名:<input type="text" name="txtName"  value="<%=LoginUserName%>"/><br />
14         密码;<input type="password" name="txtPwd" /><br />
15         <input type="submit" value="登录" />
16         
17     </div>
18     </form>
19 </body>
20 </html>

处理cookie的详细代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 
 8 namespace CZBK.ItcastProject.WebApp._2015_5_31
 9 {
10     public partial class Login : System.Web.UI.Page
11     {
12         public string LoginUserName { get; set; }
13         protected void Page_Load(object sender, EventArgs e)
14         {
          //如果是post请求
15 if (IsPostBack) 16 { //从前端获取txtname的值,存放在cookie中,并且分配一个有效期 17 string userName = Request.Form["txtName"]; 18 //写到Cookie中. Response 写 19 Response.Cookies["userName"].Value = Server.UrlEncode(userName); 20 Response.Cookies["userName"].Expires = DateTime.Now.AddDays(7); 21 22 }//如果是get请求,cookie缓存区取出已经存储的值 23 else 24 { 25 //读Cookie。 Request 读 26 if (Request.Cookies["userName"] != null) 27 { 28 string name =Server.UrlDecode(Request.Cookies["userName"].Value); 29 LoginUserName = name; 30 Response.Cookies["userName"].Value = Server.UrlEncode(name); 31 Response.Cookies["userName"].Expires = DateTime.Now.AddDays(7); 32 } 33 } 34 } 35 } 36 }

猜你喜欢

转载自www.cnblogs.com/wangjinya/p/10528328.html