Você está na página 1de 25

ASP.

Net State Management


IT 4203 Advanced Web Development

Jack G. Zheng Fall 2010

State and HTTP

In information processing, a state is the complete set of properties transmitted by an object to an observer. An information system or protocol that relies upon state is said to be stateful. One that does not is said to be stateless. Or:

Stateful: the state is maintained at different times in a process. For example, phone calls are stateful. Stateless: the state cannot be maintained at different times in a process. For example, HTTP is stateless.

HTTP protocol is stateless. In other words, HTTP does not remember.


HTTP servers treats each request as an independent transaction that is unrelated to any previous or subsequent requests. HTTP itself does not provide mechanisms to maintain state information for each request/response. Application level statement management is needed.
2

Techniques for Storing and Sharing Information Between HTTP Requests


Persistent Server side Temporary

Database, File, Session (In-Process Session (SqlServer Mode), Application Mode) Persistent cookie Session cookie. URL parameter (URL rewriting), Hidden Field
3

Client side

Server Side vs. Client Side


If the state management information is stored on the client, the client submits the information to the server with each request.

If the state management information is stored on the server, the server stores the information, but tracks the client by a unique session id, using a client-side state management technique.
4

Client Side State Management

Features

Doesn't use server resources. More data is transmitted every time. Usually for simple type data. Limited security.

Basic options

HiddenField: HTML hidden fields store data without displaying that data (still accessible in HTML source code). This data is sent back to the server in HTTP post. ViewState: ViewState is an ASP.Net feature used to track control values between page post-backs. Custom values can be added to view state. Cookies: cookies store information on the client computer. The browser sends them to the server with every page request. Cookies are the best way to store state data that must be available for multiple Web pages on an entire Web site. Query strings (URL parameter): these values are visible and can be changed by users.
5

Hidden Field (Variable)

HiddenField is transformed into HTML hidden variable

Note: this works only with HTTP Post

Define a control in the .aspx page


<input type="hidden" name="HiddenField1" id="HiddenField1" value=1" />

<asp:HiddenField ID="HiddenField1" Value="1" runat="server" />

Read and set the value in code-behind


int clicks = Int32.Parse(this.HiddenField1.Value); clicks++; this.HiddenField1.Value = clicks.ToString(); this.Label2.Text = "<h2>Button 2 has been clicked " + clicks + " time(s)</h2>";
6

ViewState

ViewState is an ASP.Net implementation of page level information storing between post-backs.

It is implemented as an HTML hidden variable.

Example
Store a value in the ViewState.

if (!IsPostBack) ViewState["clicks"] =0; else {

Retrieve a value in ViewState using the parameter name. Note that the value retrieved is a generic Object. Need to cast to appropriate type.

int clicks=Int32.Parse(ViewState["clicks"].ToString()); clicks++; this.Label1.Text = "<h2>Button 1 has been clicked "+clicks+" time(s)</h2>"; ViewState["clicks"] = clicks;

}
7

Cookies

A HTTP Cookie is a small piece of textual information stored by the browser on the client computer. Cookie facts

Cookie is a name-value pair text Cookie is sent with HTTP headers Cookie is stored on the client side, but users can reject or delete cookies. Cookie has restrictions (number, size, duration, domain, path, etc.)

For more information about cookies


http://en.wikipedia.org/wiki/HTTP_cookie http://www.allaboutcookies.org http://www.cookiecentral.com/faq/


8

Persistent Cookies and Session Cookies

Persistent cookies are save to a designated folder/file by the browser.

Each cookie can be given an expiry (expiration date/time); it will be deleted by the browser after it expires.

Session cookies are not saved to the local computer disk; it only exists in the memory for the duration of the browser.

Session cookies expire when the browser window is closed Session cookies may be shared by multiple browser windows that share the same session. In this case, all related browser windows need to be closed. Commonly, cookies without expiry set will be treated as session cookies
9

Cookie Life Cycle


Server side Client Computer
Persistent Cookie
Initial requests without cookies Response to set persistent cookies

Session Cookie

ASP.Net
Response to set session cookies Subsequent requests: Cookie is sent with HTTP header

Cookies expire at a certain time: persistent cookies has a defined expiration date/time; session cookies expire when the browser is closed.
10

ASP.Net Cookie API

System.Web.HttpCookie is the class that provides functionalities to work with cookies Set a cookie
HttpCookie cookie1 = new HttpCookie("clicks", 1); cookie1.Expires = DateTime.Now.AddDays(7); Response.Cookies.Add(cookie1);
This makes the cookie a persistent cookie for 7 days.

Read a cookie

Save the cookie on the client with the response.

int clicks = int.Parse(Request.Cookies["clicks"].Value);

Cookie values are of the string type.

Delete a cookie

Cookies are sent to servers in HTTP headers.

Set the expiry earlier than current time (client time) will instruct the browser to delete the cookie.

recookie1.Expires = DateTime.Now.AddYears(-30);
11

Cookie Use Practices

Cookies only handle simple data type

Numbers, characters, strings

Persistent cookies are often used to save user preferences or convenience information on a private computer

Provide users with the options to save information for convenience on their private computers. For example, https://zimbra.spsu.edu/

Client computers might block cookies

Need to check whether a browser accepts cookies: http://msdn.microsoft.com/en-us/library/ms178194.aspx


12

Client-Side Techniques Comparison


Technique Cookie When to use?
Used to store small amounts of information on the client and security is not an issue. Use when you need to store small amounts of information for a page that will post back to itself or to another page, and when security is not an issue. Use when you need to store small amounts of information for a page that will post back to itself with basic security.

Note
Persistent cookies are saved even the computer is shut down, a unique feature that can provide convenience.

Form hidden variable (HiddenField) ViewState

URL parameter

Use when you are transferring small amounts of information from one page to another and security is not an issue.

You can use query strings only if you are requesting the same page, or another page via a link.
13

Server Side

State information can also be saved on the server side (in server memory or other processes). Features

Server-side options for storing page information typically have higher security than client-side options they can use more Web server resources, which can lead to scalability issues when the size of the information store is large. More complex data types (such as objects, collections, ADO.Net) can be stored.

Choices

Session: user/visit specific Application: the same to all users/visits

14

Session

Session

A serial of consecutive and related requests and responses between the server and a client, in a certain duration and scope. These requests and responses in the same session share information stored on the server side. The same session can span multiple browser windows or tabs

Session id

Each current active session is identified by a unique ID (session id), which is passed with every HTTP request Session ids can be sent with a session cookie or part of a URL Session id reuse: see http://support.microsoft.com/kb/899918

Session duration

The session duration is set by the server. A session expires when there is no activity for a certain amount of time (idle time). Client computers can also end a session by abandoning the session id
15

Session Life Cycle (Cookie Used)


Server side
Server Memory or Other Services 1. New session created

Client Browser
1st request
2. Response: session id is set

Session Cookie

ASP.Net
Put data into memory Read data from memory

3. Subsequent requests: session id is sent to server

Session ends after a certain idle period

Session ends when the browser is closed*

16

ASP.Net Session API

Session data are stored in a System.Web.SessionState.SessionStateItemCollection object which is exposed through the HttpContext.Session property. In an ASP.NET page, the current session variables are exposed through the Session property of the Page object (this.Session). Store data in session
Session variables can be any valid .NET Framework type.

int clicks=1; PostItem pitem = new PostItem(); this.Session["clicks"] = clicks; Session variables are indexed by the name of this.Session["item"] = pitem; the variable or by an integer index. There is no

Read data from session

need to declare a session variable or explicitly add it to the collection.

int clicks = int.Parse(Session["clicks"].ToString()); PostItem item1 = (PostItem)Session["item"];


Any data retrieved from session is a generic Object type. It must be cast to the appropriate type.
17

Other Session Members

Session.SessionID

A unique id for each current session

Session.IsNewSession

Is the current session newly created?

Session.Mode

The default is InProc, where session state is stored in memory of ASP.NET worker process.

Session.Timeout

The time allowed for idle time, default to 20 minutes

Session.CookieMode and Session.IsCookieless

Use session cookie to store session id?

Session.Abandon()

Cancels the current session

Reference

http://msdn.microsoft.com/en-us/library/ah635ck5(v=VS.100).aspx
18

Session Settings in Web.config


<configuration> <system.web> Session is maintained in memory. <sessionState mode="InProc" User session cookie to store session id. cookieless=false" timeout="30" /> 30 minutes. </system.web> </configuration>
19

Application

ASP.NET Application state is a global storage mechanism for data that needs to be accessible to all pages and users in a Web application.

Application works in a similar way as Session, only in a bigger scope. Session state is specific to a single user session, while application state is shared by all users and sessions within the same application context (an application is defined by ASP.Net and IIS).

Duration

Data stored in the Application object is not permanent. It is temporarily held in memory on the server. Application state can be lost any time the application is restarted. For example, IIS might restart your ASP.NET application.

Usage

Application state is a great place to store small amounts of often-used data that is not user-specific but is global in nature, for example, a counter of user visits (sessions).
20

ASP.Net Application API

Application state is stored in an instance of the HttpApplicationState class that is provided through the Page.Application property. Save information to Application
int clicks=1; PostItem pitem = new PostItem(); this.Application["clicks"] = clicks; this.Application["item"] = pitem;
Application context can store any valid .NET Framework type.

Application data is indexed by the name of the variable or by an integer index.

Read data from Application context


int clicks = int.Parse(Application["clicks"].ToString()); PostItem item1 = (PostItem)Application["item"];
Any data retrieved from Application is a generic Object type. It must be cast to the appropriate type.
21

Summary: Session and Cookie


Technique
Security
Duration

Session
High
Server defined duration: usually 20 minutes to a few hours. Session ends typically because of timeout or browser closure. All pages in the same application, for a single user and computer. Use server resources; minimum network resource. Temporary data between page transition in a highly interactive session: shopping, chatting, user login status, etc.

Cookie
Low
Simple Persistent cookie can stay on client computers much longer, even the computer is shut down. Bigger. Scope can be defined at directory or domain level. Use client resources; use more network resources. User preferences, activity tracking, convenience

Data complexity Can store complex data

Scope

Resource consumption Typical usage

Official recommendations

http://msdn.microsoft.com/en-us/library/z1hkazw7(v=VS.90).aspx22

Common Stateful Web Applications

User authentication

Maintain the authenticated status until logout. Remember users and user information

Personalization and customization


Background, text size, theme, etc. Remember browser type and settings

Activity tracking

Search/browsing history, visit counter, shopping cart, shopping list, etc. Record user input and choices in a multi-step (page) process, for example, survey, application form, etc.
23

Summary

Key Concepts

State: stateful, stateless Server-side and client-side state management HTTP cookie: persistent cookie, session cookie Session Application

Key skills

Use cookies to store information between requests Use server session or application to store information between requests Understand the differences between state management techniques and be able to choose the appropriate one for various situations. Apply the concepts and basic techniques to some common web applications: user authentication, customization, shopping cart, activity tracking, etc.

24

Key Readings and Resources

ASP.NET State Management Overview

http://msdn.microsoft.com/en-us/library/75x4ha6s(v=VS.90).aspx

ASP.NET Cookies Overview

http://msdn.microsoft.com/en-us/library/ms178194(v=VS.90).aspx

ASP.NET Session State Overview

http://msdn.microsoft.com/en-us/library/ms178581(v=VS.90).aspx

ASP.NET State Management Recommendations

http://msdn.microsoft.com/en-us/library/z1hkazw7(v=VS.90).aspx

Understanding State Management

http://www.beansoftware.com/ASP.NET-Tutorials/Understanding-StateManagement.aspx

25

Você também pode gostar