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 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.
Sessionis 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.Cookieshould 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.Cacheobject 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.Applicationobject 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中,有很多种保存信息的对象.例 ...
随机推荐
- python提供了一个进行hash加密的模块:hashlib
python提供了一个进行hash加密的模块:hashlib下面主要记录下其中的md5加密方式 import hashlib data1 = 'sada' #####字母和数字 m = hashlib ...
- MySQL中的聚合函数
创建student表 CREATE TABLE IF NOT EXISTS `student` ( `id` int(4) unsigned NOT NULL AUTO_INCREMENT, `nam ...
- windows Objective-C模拟环境搭建
安装GNUstep GNUstep Windows Installer提供了Windows平台下的Objective-C的模拟开发环境,一共有四个软件包,其中GNUstep System和GNUste ...
- IOS 多线程的一些总结
IOS 多线程 有三种主要方法 (1)NSThread (2)NSOperation (3)** 下面简单介绍这三个方法 1.NSThread 调用方法如下: 如函数需要输入参数, ...
- 【BZOJ3930】[CQOI2015]选数 莫比乌斯反演
[BZOJ3930][CQOI2015]选数 Description 我们知道,从区间[L,H](L和H为整数)中选取N个整数,总共有(H-L+1)^N种方案.小z很好奇这样选出的数的最大公约数的规律 ...
- Online Judge(字符串-格式)
Online Judge Problem Description Ignatius is building an Online Judge, now he has worked out all the ...
- 巨蟒python全栈开发django10:ajax&&登录认证
通过题目进行知识点回顾: 聚合查询 From django.db.models import Avg,Min,Max,F,Q,Count,Sum #查询书籍的平均值 Ret= Models.Book. ...
- JavaScript数据结构与算法-队列练习
队列的实现 // 队列类 function Deque () { this.dataStore = []; this.enqueueFront = enqueueFront; this.enqueue ...
- 使用jquery的ajax方法获取下拉列表值
AJAX 是一种用于创建快速动态网页的技术. 通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新.这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新,用户体验非常好. ...
- css选择器的权重
权重会叠加!