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
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 HttpHandler
s 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的更多相关文章
- 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 ...
- asp.net Application、 Session、Cookie、ViewState、Cache、Hidden 的区别
这些对象都是用来保存信息的,包括用户信息,传递值的信息,全局信息等等.他们之间的区别: 1.Application对象 Application用于保存所有用户的公共的数据信息,如果使用Applicat ...
- Application,Session,Cookie,ViewState和Cache区别
在ASP.NET中,有很多种保存信息的内置对象,如:Application,Session,Cookie,ViewState和Cache等.下面分别介绍它们的用法和区别. 方法 信息量大小 作用域和保 ...
- 转载ASP.NET 状态管理Application,Session,Cookie和ViewState用法
转载原地址 http://www.cnblogs.com/cuishao1985/archive/2009/09/24/1573403.html ASP.NET状态管理 APPlication,Ses ...
- ASP.NET Application,Session,Cookie和ViewState等对象用法和区别 (转)
在ASP.NET中,有很多种保存信息的内置对象,如:Application,Session,Cookie,ViewState和Cache等.下面分别介绍它们的用法和区别. 方法 信息量大小 作用域和保 ...
- 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 ...
- [ASP.net教程]ASP.NET保存信息总结(Application、Session、Cookie、ViewState和Cache等)
以下是关于ASP.NET中保存各种信息的对象的比较,理解这些对象的原理,对制作完善的程序来说是相当有必要的(摘至互联网,并非原创--xukunping)在ASP.NET中,有很多种保存信息的对象.例如 ...
- (转)Application, Session, Cookie, Viewstate, Cache对象用法和区别
================================================================================ 1.Applicati ...
- ASP.NET保存信息总结(Application、Session、Cookie、ViewState和Cache等)
以下是关于ASP.NET中保存各种信息的对象的比较,理解这些对象的原理,对制作完善的程序来说是相当有必要的(摘至互联网,并非原创--xukunping) 在ASP.NET中,有很多种保存信息的对象.例 ...
随机推荐
- java.lang.IllegalArgumentException: Invalid 'log4jConfigLocation 解决办法
MyEclipse 启动tomcat 报错: java.lang.IllegalArgumentException: Invalid 'log4jConfigLocation' parameter: ...
- supervisor 与 yii定时任务
https://www.jianshu.com/p/9abffc905645 https://www.cnblogs.com/ajianbeyourself/p/5534737.html https: ...
- Android开发:《Gradle Recipes for Android》阅读笔记1.4
在android studio下可以使用gradle视图运行gradle. gradle任务被分别组织在不同目录下,如android,build,install. 需要执行特定的任务只要双击任务名称. ...
- ADO.NET详细学习笔记《一》
目录 ADO.NET和ADO的区别 ADO.NET的五大核心对象 Connection对象 Command对象 DataAdapter对象,DataSet对象 DataReader对象 [1]ADO. ...
- java笔记十:java中的反射
Java中,反射是一种强大的工具.它使您能够创建灵活的代码,这些代码可以在运行时装配,无需在组件之间进行源代表链接.反射允许我们在编写与执行时,使我们的程序代码能够接入装载到JVM中的类的内部信息,而 ...
- HDU1688(Sightseeing)
题目链接:传送门 题目大意:给你一幅图(单向边),找出从起点到终点有多少条不同路径(最短路或者比最短路长度大1) 题目思路:二维dijkstra,真的是要对dijkstra理解非常透彻才行,距离数组d ...
- A C Program to demonstrate adjacency list representation of graphs
w Graph and its representations - GeeksforGeekshttp://www.geeksforgeeks.org/graph-and-its-representa ...
- Service Name Port Number Transport Protocol tcp udp 端口号16bit
https://en.wikipedia.org/wiki/Dynamic_Host_Configuration_Protocol The DHCP employs a connectionless ...
- 解决table插入tr错位
table中用JavaScript插入隐藏(即display="none";)的tr时,别用display="block";换成display="&q ...
- python并发之IO模型(一)
事件驱动模型 协程:遇到IO操作就切换. 但什么时候切回去呢?怎么确定IO操作完了? 很多程序员可能会考虑使用“线程池”或“连接池”.“线程池”旨在减少创建和销毁线程的频率,其维持一定合理数量的线程, ...