cookie 介绍: cookie 的简单介绍就是把用户的登录信息缓存在本机的浏览器中, 且最大容量为 4KB, 但是这种存储是不安全的, 通常一般会进行加密处理, 但是依旧不能做到安全, 所以一般要优先考虑网站的安全性以及应用场景.
aspx 前端代码:
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="CZBK.ItcastProject.webApp._2015_5_31.Login" %>
- <!DOCTYPE html>
- <HTML xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>
- </title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- 用户名:
- <input type="text" name="txtName" value="<%=LoginUserName%>" />
- <br />
- 密码;
- <input type="password" name="txtPwd" />
- <br />
- <input type="submit" value="登录" />
- </div>
- </form>
- </body>
- </HTML>
处理 cookie 的详细代码:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- namespace CZBK.ItcastProject.WebApp._2015_5_31
- {
- public partial class Login : System.Web.UI.Page
- {
- public string LoginUserName { get; set; }
- protected void Page_Load(object sender, EventArgs e)
- {
- // 如果是 post 请求
- if (IsPostBack)
- { // 从前端获取 txtname 的值, 存放在 cookie 中, 并且分配一个有效期
- string userName = Request.Form["txtName"];
- // 写到 Cookie 中. Response 写
- Response.Cookies["userName"].Value = Server.UrlEncode(userName);
- Response.Cookies["userName"].Expires = DateTime.Now.AddDays(7);
- }// 如果是 get 请求, cookie 缓存区取出已经存储的值
- else
- {
- // 读 Cookie. Request 读
- if (Request.Cookies["userName"] != null)
- {
- string name =Server.UrlDecode(Request.Cookies["userName"].Value);
- LoginUserName = name;
- Response.Cookies["userName"].Value = Server.UrlEncode(name);
- Response.Cookies["userName"].Expires = DateTime.Now.AddDays(7);
- }
- }
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2986683.html