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中,有很多种保存信息的对象.例 ...
随机推荐
- windows 下XAMPP 使用Nginx替代apache作为服务器
说实话, 在windows下使用Nginx 着实有点不太方便, 但因项目需求, 又不想换系统(虽然可以搞个虚拟机玩), 只能用Nginx了 好了, 不多说了. 开始... 首先我用的是xampp包(A ...
- IO-Polling的代码分析
在前一篇文章<IO-Polling实现分析与性能评測>中提到了IO-Polling与中断的原理差别,并通过两种模式下NVMe SSD的性能測试对两者进行了对照. 这篇文章将深入到IO-Po ...
- Codeforces Beta Round #25 (Div. 2)--A. IQ test
IQ test time limit per test 2 seconds memory limit per test 256 megabytes input standard input outpu ...
- Observable观察者模式的使用
今天我们公司封装的类中没有加上Observable观察者模式,但是很多地方需要用到Observable观察者模式 接下来就向大家介绍一下我的使用吧! 在介绍之前我们写了一个方法 public clas ...
- jmeter对响应结果做正则、json、xpath结果测试
上面的返回结果可用于关联取值测试 具体用法详见http://www.cnblogs.com/xinjing-jingxin/p/8554338.html http://goessner.net/art ...
- COGS 693. [SDOI2005]Antiprime数 唯一分解定理逆用
693. Antiprime数 ★★ 输入文件:antip.in 输出文件:antip.out 简单对比 时间限制:1 s 内存限制:128 MB 如果一个自然数n(n>=1), ...
- Building Shops
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others) Total Submissi ...
- Xamarin.Forms学习之位图(一)
在开始我的分享之前呢,让我先问下我的问题: 1.最近更新了Xamarin 4.1.1.3,我想问下版本更新信息在哪里看? 2.更新后我新建的项目没有UWP项目了(虽然没有用过,但是我想确认是4.1.1 ...
- Constructor Acquires, Destructor Releases Resource Acquisition Is Initialization
w https://zh.wikipedia.org/wiki/RAII RAII要求,资源的有效期与持有资源的对象的生命期严格绑定,即由对象的构造函数完成资源的分配(获取),同时由析构函数完成资源的 ...
- Linux中的服务管理
RPM包默认安装的服务 查看已安装的服务: chkconfig --list 默认安装位置: /etc/init.d 启动脚本 /etc/sysconfig 初始化环境配置文件 /etc 配置文件位 ...