https://devshop.wordpress.com/2008/04/10/how-to-choose-from-viewstate-sessionstate-cookies-and-cache/

Problem with Web Applications

Web applications are stateless, means once a web page is rendered from
server to client, nothing in the page remains on server and the next
time user submits the page, the page will be called and created from
scratch.

ASP.NET provides following solutions to solve this problem:

1- Viewstate
2- Session Variables
3- Application Variables
4- Cache
5- Cookies

Now the question arises that when to use what?

1- Viewstate

Viewstate is a hidden fields in an ASP.NET page, contains state of those controls on a page whose “EnableViewstate” property is “true”.
You can also explicitly add values in it, on an ASP.NET page like:
Viewstate.Add( “TotalStudents”, “87” );
Viewstate should be used when you want to save a value between different
round-trips of a single page
as viewstate of a page is not accessible
by another page.
Because Viewstate render with the page, it consumes bandwidth, so be
careful to use it in applications to be run on low bandwidth.

2- Session Variable

Session variables are usually the most commonly used.
When a user visits a site, it’s sessions starts and when the user become idle or leave the site, the session ends.
Session variables should be used to save and retrieve user specific information required on multiple pages.
Session variables consumes server memory, so if your may have a huge
amount visitors, use session very carefully and instead of put large
values in it try to put IDs and references

3- Application variables

Application variables are shared variables among all users of a web application
Application variables behave like static variables and they are
substitute of static variables as static variables are stateless in web
applications
Only shared values should be persisted in Application variables, and as
soon as they are not in use they should be removed explicitly.

4- Cache

Cache is probably the least used state feature of ASP.NET.
Cache is basically a resource specific state persistence feature, means
unlike session it stick with resource instead of user, for instance:
pages, controls
etc.
Cache should be used or frequently used pages, controls, and data structures
Data cache can be used to cache frequently used list of values e.g. list of products

6- Cookies

Cookies are some values saved in browsers for a particular website o publicly accessible
The purpose of cookies is to help websites to identify visitors and retrieve their saved preferences
Cookies are also used to facilitate auto login by persisting user id in a cookie save in user’s browser
Because cookies have been saved at client side, they do not create
performance issues but may create security issues as they can be hacked
from browser

Finally remember the following points on your finger-tips:

1- Viewstate is bandwidth hungry
2- Session variables are memory hungry as per number of users
3- Applications variables are shared
4- Cache is memory hungry as per number of resources
5- Cookies are the least secure

https://stackoverflow.com/questions/2883149/viewstate-vs-session-maintaining-object-through-page-lifecycle

If the search object isn't huge in size, then go with using a ViewState. A ViewState is perfect if you only want the object to live for the current page's lifecycle.

A session object is also fine to use, but obviously once the search object is in there, it will be around for longer the page's lifecycle.

Also, one thing I do with ViewState/Session objects is wrap their access with a property:

public object GetObject
{
get
{
return ViewState["MyObject"];
}
set
{
ViewState["MyObject"] = value;
}
}

I tend to find it cleaner to do it this way. Just change the above code to fit your needs.

viewstate不能跨页面,是在单页的多个流程中被使用

session存储和用户相关的信息

cookie   https://docs.microsoft.com/en-us/dotnet/api/system.web.httpresponse.cookies?view=netframework-4.7.2

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2

 

A little late here, but here's something I just discovered.

@Phillipe Leybaert and @CSharpAtl are both incorrect. HttpApplication's Session property exhibits different behaviour than does that of the property HttpContext.Current.Session. They will both return a reference to the same HttpSessionState instance if one is available. They differ in what they do when there is no instance of HttpSessionState available for the current request.

Not all HttpHandlers provide session state. To do so, the HttpHandler must implement [one or both?] the marker interfaces IRequiresSessionState or IReadOnlySessionState.

HttpContext.Current.Session simply returns null if there is no session available.

The HttpApplication's implementation of the Session property throws an HttpException with the message Session state is not available in this context. rather than returning a null reference.

Some examples of HttpHandler that do not implement session are the default handlers for normally static resources, such as image and CSS files. Any reference to the HttpApplication's Session property in such cases (as in global.asax event handlers) will result an HttpException being thrown.

Needless to say, the unexpected HttpException provides a WTF?! moment if you're not expecting it.

The Session property of the HttpApplication class is implemented thus (from Reflector):

What is the difference between these two HttpContext.Current.Session and Session - asp.net 4.0

 

They're effectively the same, in that they will access the same Session data.

The reason you can call Session in your code-behind is because ASP.Net pages by default extend the System.Web.UI.Page type. This has a Session public property. If you look at the code for this in Reflector you can see that it just calls HttpContext.Current.Session itself (through its own Context property).

In other classes you will not have access to that property, but you can use HttpContext.Current.Session to access the session data instead, as long as you're running in the context of a web application.

Well the object the properties return is the same, but if a session doesn't exist HttpContect.Current.Session will return null while Page.Session will throw an HttpException.

封装一个泛型的session使用

https://www.codeproject.com/Tips/559508/%2FTips%2F559508%2FSession-Management-With-Generics

Cache VS Session VS cookies?

State management is a critical thing to master when coming to Web world from a desktop application perspective.

  • Session is used to store per-user information for the current Web session on the server. It supports using a database server as the back-end store.
  • Cookie should be used to store per-user information for the current Web session or persistent information on the client, therefore client has control over the contents of a cookie.
  • Cache object is shared between users in a single application. Its primary purpose is to cache data from a data store and should not be used as a primary storage. It supports automatic invalidation features.
  • Application object is shared between users to store application-wide state and should be used accordingly.

If your application is used by a number of unauthenticated users, I suggest you store the data in a cookie. If it requires authentication, you can either store the data in the DB manually or use ASP.NET profile management features.

ViewState Vs Session … maintaining object through page lifecycle

First of all Viewstate is per page where as the session exists throughout the application during the current session, if you want your searchobject to persist across pages then session is the right way to go.

Second of all Viewstate is transferred as encrypted text between the browser and the server with each postback, so the more you store in the Viewstate the more data is going down to and coming back from the client each time, whereas the session is stored server side and the only thing that goes back and forth is a session identifier, either as a cookie or in the URL.

Whether the session or viewstate is the right place to store your search object depends on what you are doing with it and what data is in it, hopefully the above explanation will help you decide the right method to use.

How to store string in a cookie and retrieve it

Writing a cookie

HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now; // Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddYears(50); // For a cookie to effectively never expire // Add the cookie.
Response.Cookies.Add(myCookie); Response.Write("<p> The cookie has been written.");

Reading a cookie

HttpCookie myCookie = Request.Cookies["MyTestCookie"];

// Read the cookie information and display it.
if (myCookie != null)
Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
Response.Write("not found");

How to choose from Viewstate, SessionState, Cookies and Cache的更多相关文章

  1. User control's property loses value after a postback

    User control's property loses value after a postback All variables (and controls) are disposed at th ...

  2. asp.net Application、 Session、Cookie、ViewState、Cache、Hidden 的区别

    这些对象都是用来保存信息的,包括用户信息,传递值的信息,全局信息等等.他们之间的区别: 1.Application对象 Application用于保存所有用户的公共的数据信息,如果使用Applicat ...

  3. Application,Session,Cookie,ViewState和Cache区别

    在ASP.NET中,有很多种保存信息的内置对象,如:Application,Session,Cookie,ViewState和Cache等.下面分别介绍它们的用法和区别. 方法 信息量大小 作用域和保 ...

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

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

  5. ASP.NET Application,Session,Cookie和ViewState等对象用法和区别 (转)

    在ASP.NET中,有很多种保存信息的内置对象,如:Application,Session,Cookie,ViewState和Cache等.下面分别介绍它们的用法和区别. 方法 信息量大小 作用域和保 ...

  6. ASP.NET保存信息总结(Application、Session、Cookie、ViewState和Cache等) ZT

    http://www.cnblogs.com/ranran/p/4065619.html http://www.cnblogs.com/jxlsomnus/p/4450911.html 以下是关于AS ...

  7. [ASP.net教程]ASP.NET保存信息总结(Application、Session、Cookie、ViewState和Cache等)

    以下是关于ASP.NET中保存各种信息的对象的比较,理解这些对象的原理,对制作完善的程序来说是相当有必要的(摘至互联网,并非原创--xukunping)在ASP.NET中,有很多种保存信息的对象.例如 ...

  8. (转)Application, Session, Cookie, Viewstate, Cache对象用法和区别

    ================================================================================         1.Applicati ...

  9. ASP.NET保存信息总结(Application、Session、Cookie、ViewState和Cache等)

    以下是关于ASP.NET中保存各种信息的对象的比较,理解这些对象的原理,对制作完善的程序来说是相当有必要的(摘至互联网,并非原创--xukunping) 在ASP.NET中,有很多种保存信息的对象.例 ...

随机推荐

  1. 队列实现 (双向循环链表 C++)

    队列是非常easy的.可是用数组实现可能更好点. . (事实上我认为数组在多个队列的时候更难) 然后我是第一次写双向循环链表.指向太乱了. 我这里是依照自己的想法.建立了一个头节点,一个尾节点,然后依 ...

  2. java中InputStream转化为byte[]数组

    //org.apache.commons.io.IOUtils.toByteArray已经有实现 String filePath = "D:\\aaa.txt"; in = new ...

  3. Kotlin——中级篇(一):类(class)详解

    在任何一门面向对象编程的语言里,类(class)是非常基础.但也是非常重要的一项组成,通俗的说就是万般皆对象,而所说的对象就是我们生成的类.Kotlin也是如此,下面详细为大家介绍Kotlin中的类的 ...

  4. .NET调用JAVA的WebService方法

    调用WebService,最简单的办法当然是直接添加WEB引用,然后自动产生代理类,但是在调用JAVA的WebService时并没有这么简单,特别是对于SoapHeader的处理,在网上也有相关资料, ...

  5. 获取html元素所在页面的坐标

    function findPosition(oElement) { var x2 = 0; var y2 = 0; var width = oElement.offsetWidth; var heig ...

  6. _ 下划线 Underscores __init__

    Underscores in Python https://shahriar.svbtle.com/underscores-in-python Underscores in Python This p ...

  7. 【python】-- Django Form

    Django  Form Django的Form主要具有一下几大功能: 生成HTML标签 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容(自定义样式) 一.F ...

  8. servle 3.0 新特性之一 对上传表单的支持

    1. 上传 * 上传对表单的要求: > method="post" > enctype="multipart/form-data",它的默认值是:a ...

  9. 20170401 ABAP调用CIS webservice

    问题: SAP  abap SRM java  调webservice 不通, CIS java  这边的webservice 可以通, WHY? key:请求头,系统框架的问题, LF:因为请求头的 ...

  10. A+B和C (15)

    时间限制 1000 ms 内存限制 32768 KB 代码长度限制 100 KB 判断程序 Standard (来自 小小) 题目描述 给定区间[-2的31次方, 2的31次方]内的3个整数A.B和C ...