1,HTTP协议是无状态的。服务器不会记住上次给浏览器的处理结果,如果需要上次处理结果(上次状态)就需要浏览器把处理结果值(上次状态)再次给服务器。

2,URL传值:通过URL参数或者通过Form表单进行页面件的传值 (不能做到很自由的存取和读取,而且不安全)

3,Cookie :①Cookie可以用来进行更加自由的数据的存取和读取。

        ②Cookie是和站点相关的,自己域名写的只有自己的域名才可以读取。

        ③客户端向服务器发送请求的时候 处理发送Form表单信息以外还会把和站点有关的所有的Cookie发送给服务器,是强制的。

        ④服务器返回的数据处理HTML数据以外,还会返回修改的Cookie,浏览器拿到修改后的Cookie更新到本地的Cookie

        ⑤服务器端使用Cookie案例,记住用户名功能:

        A,设置页面值: Response.SetCookie(new HttpCookie("UserName",username))

        B,读取页面值: username=Request.Cookies["UserName"].Value

        ⑥浏览器关闭以后Cookie的声明周期到期,也就是Cookie的默认生命周期是浏览器的生命周期。可以通过设置Expires属性设置Cookie的过期时间:Cookie.Expires=DateTime.Now.AddDays(-1)

        ⑦Cookie在客户端是以键值对存在的

4,Cookie缺点:①客户端额可以手动清楚Cookie 所以Cookie里面存放的信息是可有可无的信息

          ②浏览器对 Cookie 的大小有限制,因此只有不超过 4096 字节才能保证被接受

          ③机密信息不能放到Cookie里面

          ④Cookie不能跨浏览器

5,Cookie的写和读: A,新建CookieTest.html页面并添加 两个按钮分别用于Cookie的读和写

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form>
<input type="submit" name="Read" value="读取Cookie" />&nbsp;
<input type="submit" name="Write" value="写入Cookie" /> <br />
读取出来的Cookie: $Model.CookieValue
</form>
</body>
</html>

           B,建立对应的CookieTest.ashx页面 实现Cookie的新建写入本地以及读取Cookie的值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace HttpNoStatus
{
/// <summary>
/// HttpCookie 的摘要说明
/// </summary>
public class CookieTest : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html"; //if else 判断是点击的那个按钮
if (!string.IsNullOrEmpty(context.Request["Read"]))
{
if (context.Request.Cookies["Age"] != null)
{
HttpCookie cookie = context.Request.Cookies["Age"];
string strValue = cookie.Value;
var data = new { CookieValue = strValue }; //加载模板页面并传递 Cookie Value的值
string strHtml = Common_Nvelocity.RenderHTML("CookieTest.html", data);
context.Response.Write(strHtml);
}
else
{
context.Response.Write("cookie 不存在");
}
}
else if (!string.IsNullOrEmpty(context.Request["Write"]))
{
//写入新的Cookie
HttpCookie acookie = new HttpCookie("Age");
acookie.Value = "";
acookie.Expires = DateTime.MaxValue;
context.Response.Cookies.Add(acookie); //Cookie不存在 直接加载模板页面
string strHtml = Common_Nvelocity.RenderHTML("CookieTest.html", null);
context.Response.Write(strHtml); } else
{
//第一次加载页面
string strHtml = Common_Nvelocity.RenderHTML("CookieTest.html", null);
context.Response.Write(strHtml);
}
} public bool IsReusable
{
get
{
return false;
}
}
}
}

6,Cookie最主要的一个功能是保存用户的登陆名,这样用户在下次登陆的时候系统就可以自动填写登陆名称

           A,新建LoginCookie.html页面,页面中添加我们经常见到的 用户名,用户密码,登陆  

             登陆页面第一次加载的时候,设置默认的登陆名为空,登陆成功以及再次登陆的时候系统就自动补充登陆用户名

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form action="LoginCookie.ashx" method="post">
<table>
<tr>
<td>登陆名</td>
<td>
<input type="text" name="UserName" value="$Model.LoginUser" /></td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="password" name="Password" /></td>
</tr>
<tr>
<td>
<input type="submit" name="Login" value="登陆" /></td>
<td></td>
</tr>
</table>
</form>
</body>
</html>

           B, 新建对应的LoginCookie.ashx页面,实现把用户名读取出来并写入Cookie "ckLoginUser"

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace HttpNoStatus
{
/// <summary>
/// LoginCookie 的摘要说明
/// </summary>
public class LoginCookie : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html"; //加载页面直接显示 页面
if (context.Request.Form["Login"] == null)
{
string strHtml = "";
var data = new { LoginUser = "" }; //登陆账号默认为空 //判断Cookie是否存在,如果存在 把Cookie的值传递到HTML页面,如果不存在就是默认的空
if (context.Request.Cookies["ckLoginUser"] != null)
{
data = new { LoginUser = context.Request.Cookies["ckLoginUser"].Value.ToString() };
}
strHtml = Common_Nvelocity.RenderHTML("LoginCookie.html", data);
context.Response.Write(strHtml);
}
else
{
//用户登陆,保存用户名到Cookie
HttpCookie LoginUser = new HttpCookie("ckLoginUser");
LoginUser.Value = context.Request.Form["UserName"];
LoginUser.Expires = DateTime.Now.AddDays();
context.Response.Cookies.Add(LoginUser);
//加载页面直接显示 页面
string strHtml = Common_Nvelocity.RenderHTML("LoginCookie.html", new { LoginUser = context.Request.Form["UserName"] });
context.Response.Write(strHtml);
} } public bool IsReusable
{
get
{
return false;
}
}
}
}

 7,以上方法把登陆账号以Cookie的形式存放在客户端,这样每一次的请求就可以带出用户登陆名称了

  有一种情况: 用户登陆成功以后就可以访问网站的其他所有页面,其他页面就需要先判断用户是否登陆成功。

  如果登陆成功为True放到Cookie中,这样的客户端就可以进行篡改把False改为True从而可以非法访问为授权页面了,这样放到Cookie就不安全了。

  如果登陆成功放到服务器端,那么网站的多个页面就可以直接读取到这个值,而且是安全的不会被客户端篡改的了。

8,Session原理: 把数据Value值存储在服务器端并在客户端存放Value对应的ID 。(ID,Value)都存放服务器 另外把ID以Cookie的形式存放客户端。这样就可以从客户端Cookie中抓取ID,然后从服务器端读取到ID对应的Value。

10,下面示例以Session原理实现页面判断用户是否有成功登陆:成功登陆的用户可以对特定页面进行访问、如果没有成功登陆就跳转到登陆页面。

  A. 添加类 SessionMgr.cs 在服务器端存储 键值对 ID/Value 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace HttpNoStatus
{ public class SessionMgr
{
//定义键值对,存储登陆信息
private static Dictionary<Guid, string> KeyValue = new Dictionary<Guid, string>(); //设置键值对的值
public static void SetKeyValue(Guid id, string value)
{
KeyValue[id] = value;
} /// <summary>
/// 检查客户端传递过来的键值对是否存在
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static bool IfIdExist(Guid id)
{
return KeyValue.Keys.Contains(id);
} //返回服务器端ID对应的Value值
public static string GetValue(Guid id)
{
return KeyValue[id].ToString();
} }
}

  B. 添加 LoginSession.ashx 判断用户是否登陆成功,如果登陆成功把存储对应的键值对的值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace HttpNoStatus
{
/// <summary>
/// LoginSession 的摘要说明
/// </summary>
public class LoginSession : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string strHtml = "";
//读取用户名和密码
string strUserName = context.Request.Form["txtUserName"];
string strPwd = context.Request.Form["txtPassword"];
if (strPwd == "")
{
//登陆成功,设置对应的键值对
Guid id = Guid.NewGuid(); // 产生唯一的ID
SessionMgr.SetKeyValue(id, strUserName); //id 保存在客户端cookie中
HttpCookie loginCookie = new HttpCookie("LoginCookie");
loginCookie.Value = id.ToString();
loginCookie.Expires = DateTime.Now.AddDays();
context.Response.Cookies.Add(loginCookie); //跳转到授权页面
context.Response.Redirect("AuthorizationPage.ashx"); }
else
{
//登陆失败 , 加载登陆页面
strHtml = Common_Nvelocity.RenderHTML("LoginSession.html", null);
context.Response.Write(strHtml); }
} public bool IsReusable
{
get
{
return false;
}
}
}
}

  C. Templates文件夹下添加LoginSession.html 登陆页面

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form action="LoginSession.ashx" method="post">
<table>
<tr>
<td>登陆名</td>
<td>
<input type="text" name="txtUserName" /></td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="password" name="txtPassword" /></td>
</tr>
<tr>
<td>
<input type="submit" name="Login" value="登陆" /></td>
<td></td>
</tr>
</table> </form>
</body>
</html>

  D. 添加AuthorizationPage.ashx页面,只有登陆后的账户才有权限访问这个页面

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace HttpNoStatus.Templates
{
/// <summary>
/// AuthorizationPage 的摘要说明
/// </summary>
public class AuthorizationPage : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html"; //抓取客户端 Cookie的ID值
HttpCookie loginCookie = context.Request.Cookies["LoginCookie"];
if (loginCookie != null)
{
Guid id = new Guid(loginCookie.Value); // 读取id对应的Value
string strValue = SessionMgr.GetValue(id); //输出Value值,并提示该账号是已经登陆的账号
context.Response.Write(strValue + ",您已经登陆本网站,有权限访问此页面");
} //如果Cookie不存在,则直接跳转到登页面
else
{
context.Response.Redirect("LoginSession.ashx");
}
} public bool IsReusable
{
get
{
return false;
}
}
}
}

------------------------------------------------------------gif动画演示----------------------------------------------------------------

11,上面的示例是也就是Session原理。Asp.net已经内置了Session机制,下面我们直接用ASP.NET Session实现 判断用户是否有登陆成功:

   (一般处理程序HttpHandler操作Session, 要实现IRequiresSessionState接口)

  分别添加页面: LoginSessionNew.ashx(登陆一般处理程序) , LoginSessionNew.html(登陆模板), AuthorizationPageNew.ashx(登陆后才有权限访问的页面)。

  A,LoginSessionNew.ashx(登陆一般处理程序)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState; namespace HttpNoStatus
{
/// <summary>
/// LoginSessionNew 的摘要说明
/// </summary>
public class LoginSessionNew : IHttpHandler, IRequiresSessionState
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/html";
string strHtml = "";
//读取用户名和密码
string strUserName = context.Request.Form["txtUserName"];
string strPwd = context.Request.Form["txtPassword"];
if (strPwd == "")
{
//登陆成功,直接保存Session值 context.Session["LoginUserName"] = strUserName; //跳转到授权页面
context.Response.Redirect("AuthorizationPageNew.ashx"); }
else
{
//登陆失败 , 加载登陆页面
strHtml = Common_Nvelocity.RenderHTML("LoginSessionNew.html", null);
context.Response.Write(strHtml); }
} public bool IsReusable
{
get
{
return false;
}
}
}
}

  B,Templates模板下新建LoginSessionNew.html(登陆模板)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form action="LoginSessionNew.ashx" method="post">
<table>
<tr>
<td>登陆名</td>
<td>
<input type="text" name="txtUserName" /></td>
</tr>
<tr>
<td>密码</td>
<td>
<input type="password" name="txtPassword" /></td>
</tr>
<tr>
<td>
<input type="submit" name="Login" value="登陆" /></td>
<td></td>
</tr>
</table> </form>
</body>
</html>

  C,AuthorizationPageNew.ashx(登陆后才有权限访问的页面)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState; namespace HttpNoStatus
{
/// <summary>
/// AuthorizationPageNew 的摘要说明
/// </summary>
public class AuthorizationPageNew : IHttpHandler, IRequiresSessionState
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
//检查Session是否存在 object obj = context.Session["LoginUserName"]; if (obj != null)
{
//Session存在,读取Session值,并提示该账号是已经登陆的账号
context.Response.Write(obj.ToString() + ",您已经登陆本网站,有权限访问此页面");
} //如果Session不存在,则直接跳转到登页面
else
{
context.Response.Redirect("LoginSessionNew.ashx");
}
} public bool IsReusable
{
get
{
return false;
}
}
}
}

  · ASP.NET内置Session机制同样实现了对用户是否登陆成功的判断:LoginSessionNew.ashx页面Headers中我们看到了Cookie中多了ASP.NET_SessionId

   Session机制在客户端存放了ASP.NET_SessionID

  

  · 权限访问页面,请求头中读取到了客户端Cookie中的ASP.NET_SessionID

  

12, ASP.NET的Session机制: Session依赖于Cookie , 借助Cookie在客户端浏览器中记录了ID, 在服务器端存储了Value值。

13,Session的值是放到了服务器内存中,所以Session存放小数据。

  Session(会话)有自动销毁机制,如果一段时间内浏览器没有和服务器交互,则Session会定时自动销毁。

  登陆账号后,一段时间内如果不操作 系统就会自动退出,这就是Session自动销毁了。

  

Demo 下载

  

ASP.NET 状态的传递和保存的更多相关文章

  1. [译]面向初学者的Asp.Net状态管理技术

    介绍 本文主要讲解Asp.Net应用程序中的状态管理技术(Asp.Net中有多种状态管理技术),并批判性地分析所有状态管理技术的优缺点. 背景 HTTP是无状态的协议.客户端发起一个请求,服务器响应完 ...

  2. 转载ASP.NET 状态管理Application,Session,Cookie和ViewState用法

    转载原地址 http://www.cnblogs.com/cuishao1985/archive/2009/09/24/1573403.html ASP.NET状态管理 APPlication,Ses ...

  3. ASP.NET 使用mode=”InProc”方式保存Session老是丢失,无奈改成StateServer 模式。

    http://blog.csdn.net/fox123871/article/details/8165431 session是工作在你的应用程序进程中的.asp.net进程.iis往往会在20分钟之后 ...

  4. ASP.NET页面之间传递值的几种方式(转载)

    页面传值是学习asp.net初期都会面临的一个问题,总的来说有页面传值.存储对象传值.ajax.类.model.表单等.但是一般来说,常用的较简单有QueryString,Session,Cookie ...

  5. ASP.NET状态管理的总结

    阅读目录 开始 hidden-input QueryString Cookie ApplicationState ViewState,ControlState Session Profile 各种状态 ...

  6. ASP中页面之间传递值的几种方式

    ASP.NET页面之间传递值的几种方式 页面传值是学习asp.net初期都会面临的一个问题,总的来说有页面传值.存储对象传值.ajax.类.model.表单等.但是一般来说,常用的较简单有QueryS ...

  7. ASP.NET 状态服务 及 session丢失问题解决方案总结

    ASP.NET2.0系统时,在程序中做删除或创建文件操作时,出现session丢失问题.采用了如下方法:1.asp.net Session的实现:asp.net的Session是基于HttpModul ...

  8. 转:无法向会话状态服务器发出会话状态请求请。确保 ASP.NET State Service (ASP.NET 状态服务)已启动

    今天看到一篇文章感觉不错,收藏转载下. 原文地址:http://blog.csdn.net/sntyy/article/details/2090347 版权为原作者所有 无法向会话状态服务器发出会话状 ...

  9. [转]ASP.NET 状态服务 及 session丢失问题解决方案总结

    转自[http://blog.csdn.net/high_mount/archive/2007/05/09/1601854.aspx] 最近在开发一ASP.NET2.0系统时,在程序中做删除或创建文件 ...

随机推荐

  1. Java集合框架(JCF)之collention

    一.概念:是为了实现某一目的或功能而预先提供的一系列封装好了的具有继承或实现的类与接口. 二.特点: 1.元素的类型可以不同  2.集合长度可变 3.空间不固定 三.collection与collec ...

  2. js正则表达式之解析——URL的正则表达式

    首先,此片文章并不是直接告诉你,url的正则表达式是什么,以及怎么使用这个正则表达式去解析一个URL地址,相信这种问题在网络上已经能找到很多.本文的宗旨在于教你如何理解URL的正则表达式,以达到理解正 ...

  3. thinkphp 3+ 观后详解 (1)

    最近面试了一些公司,发现自己的对于架构能力的不足,于是决定开始从最基本的代码做起.先看看大牛们怎么架构整个框架的.鉴于国外的框架比较难懂,于是就选择了国内比较流行的thinkphp来进行研究. 下面写 ...

  4. MySQL 127.0.0.1和localhost本质区别

    登录方式: [root@10-4-14-168 ~]# mysql -uroot -p Enter password: 查看权限表 mysql> SELECT user,host,passwor ...

  5. Codeforces Round #146 (Div. 1) B. Let's Play Osu! dp

    B. Let's Play Osu! 题目连接: http://www.codeforces.com/contest/235/problem/B Description You're playing ...

  6. Codeforces Educational Codeforces Round 3 D. Gadgets for dollars and pounds 二分,贪心

    D. Gadgets for dollars and pounds 题目连接: http://www.codeforces.com/contest/609/problem/C Description ...

  7. BZOJ 3930: [CQOI2015]选数 递推

    3930: [CQOI2015]选数 Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://www.lydsy.com/JudgeOnline/pro ...

  8. Codeforces Round #188 (Div. 1) B. Ants 暴力

    B. Ants Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/317/problem/B Des ...

  9. C#类的成员初始化顺序

    首先我们来看看引用类型的成员初始化过程 我们来看一个例子吧 class Program {     static void Main(string[] args)     {         Driv ...

  10. ueditor 编辑器再thinkphp中使用 解决转义问题

    在前台common.php文件中加入下面的函数就可以解决了 <?php //取消thinkphp里面的转义 if (get_magic_quotes_gpc()) { function stri ...