How to choose from Viewstate, SessionState, Cookies and Cache

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

 

 
 

Difference between Session and HttpContext.Current.Session

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");

 

 Application vs Session vs Cache

Application and Session State have a very important difference:

Application state is a data repository available to all classes in an ASP.NET application. Application state is stored in memory on the server and is faster than storing and retrieving information in a database. Unlike session state, which is specific to a single user session, application state applies to all users and sessions. Therefore, application state is a useful place to store small amounts of often-used data that does not change from one user to another

Application State Overview
Session State Overview

Caching, on the other hand, allows you to store objects in memory that require extensive server resources to create - it offers powerful features that allow you to customize how items are cached and how long they are cached - you can set extensive properties like priority and expiration.

Caching Application Data Overview

Although they might appear similar, they are distinctly separate and have different roles to play in an ASP.NET application in its broadest sense.

 

 

 

posted @ 2019-01-15 13:37  ChuckLu  阅读(823)  评论(0编辑  收藏  举报