04_StateManagement
-
Upload
nguyen-ngoc-lieu -
Category
Documents
-
view
213 -
download
0
Transcript of 04_StateManagement
-
7/27/2019 04_StateManagement
1/62
Chng: 07
State Management
Lp trnh Web
1 Lp trnh Web
-
7/27/2019 04_StateManagement
2/62
Ni dung
The Problem of State
View State
Transferring Information Between Pages
Cookies Session State
Session State Configuration
Application State
An Overview of State Management Choices
Lp trnh Web 2
-
7/27/2019 04_StateManagement
3/62
The Problem of State
In a traditional Windows program:
users interact with a continuously running application.
A portion of memory on the desktop computer is allocated
to store the current set of working information.
In a web application,
A professional ASP.NET site might look like a continuously
running application, but thats really just a clever illusion.
Lp trnh Web 3
-
7/27/2019 04_StateManagement
4/62
The Problem of State
In a typical web request, the client connects to the webserver and requests a page:
When the page is delivered, the connection is severed, and
the web server abandons any information it has about the
client
By the time the user receives a page, the web page code has
already stopped running, and theres no information left in
the web servers memory
Lp trnh Web 4
-
7/27/2019 04_StateManagement
5/62
View State
The ViewState Collection
Making View State SecureRetaining Member Variables
Storing Custom Objects
Lp trnh Web5
-
7/27/2019 04_StateManagement
6/62
View State
One of the most common ways to store information is inview state.
Web controls store most of their property values in view
state, provided the controls EnableViewState property is
set to true (which is the default).
However, view state isnt limited to web controls.
Your web page code can add bits of information directly to
the view state of the containing page and retrieve it later
after the page is posted back
The type of information you can store includes simple data
types and your own custom objects
Lp trnh Web 6
-
7/27/2019 04_StateManagement
7/62
The ViewState Collection
The ViewState property of the page provides the currentview state information.
This property is an instance of the StateBag collection
class.
The StateBag is a dictionary collection
Lp trnh Web 7
this.ViewState["Counter"] = 1;
int counter;
counter = (int)this.ViewState["Counter"];
-
7/27/2019 04_StateManagement
8/62
AView State Example
The following example is a simple counter program thatrecords how many times a button is clicked.
Lp trnh Web 8
-
7/27/2019 04_StateManagement
9/62
Making View State Secure
View state information is stored in a single jumbled stringthat looks like this
The view state information is simply patched together in
memory and converted to aBase64 string.
A clever hacker could reverse-engineer this string and
examine your view state data in a matter of seconds.
Lp trnh Web 9
-
7/27/2019 04_StateManagement
10/62
Making View State Secure
If you want to make view state more secure, you have twochoices:
Tamperproof View State
Private View State
Lp trnh Web 10
-
7/27/2019 04_StateManagement
11/62
Tamperproof View State
The idea is that ASP.NET examines all the data in viewstate, just before it renders the final page. It runs this data
through a hashing algorithm (with the help of a secret key
value).
The hashing algorithm creates a short segment of data,
which is the hash code.
This code is then added at the end of the view state data,
in the final HTML thats sent to the browser.
Lp trnh Web 11
-
7/27/2019 04_StateManagement
12/62
Tamperproof View State
When the page is posted back, ASP.NET examines theview state data and recalculates the hash code using the
same process.
It then checks whether the checksum it calculated
matches the hash code that is stored in the view state for
the page.
If a malicious user changes part of the view state data,
ASP.NET will end up with a new hash code that doesnt
match.
At this point, it will reject the postback completelyLp trnh Web 12
-
7/27/2019 04_StateManagement
13/62
Tamperproof View State
Hash codes are actually enabled by default, so if you wantthis functionality, you dont need to take any extra steps.
To disable hash codes, you can use the
enableViewStateMac attribute of the element in
the web.config or machine.config file
Lp trnh Web 13
...
-
7/27/2019 04_StateManagement
14/62
Private View State
If your view state contains some information you want tokeep secret, you can enable view state encryption
You can turn on encryption for an individual page using
the ViewStateEncryptionMode property of the Page
directive:
Or you can set the same attribute in a configuration file:
Lp trnh Web 14
...
-
7/27/2019 04_StateManagement
15/62
Private View State
You have three choices for your view state encryptionsettingalways encrypt (Always), never encrypt (Never),
or encrypt only if a control specifically requests it (Auto).
The default is Auto: the page wont encrypt its view state
unless a control on that page specifically requests it.
A control makes this request by calling the
Page.RegisterRequiresViewStateEncryption() method
Lp trnh Web 15
-
7/27/2019 04_StateManagement
16/62
Notes
Dont encrypt view state data if you dont need to do so.
The encryption will impose a performance penalty,
because the web server needs to perform the encryption
and decryption with each postback
Lp trnh Web 16
-
7/27/2019 04_StateManagement
17/62
Retaining Member Variables
Lp trnh Web 17
-
7/27/2019 04_StateManagement
18/62
Lp trnh Web 18
-
7/27/2019 04_StateManagement
19/62
Notes
The previous code example reacts to the Page.PreRenderevent, which occurs just after page processing is complete
and just before the page is rendered in HTML.
You cannot store view state information in an event
handler for the Page.Unload event. Though your code will
not cause an error, the information will not be stored in
view state, because the final HTML page output is
already rendered.
Lp trnh Web 19
-
7/27/2019 04_StateManagement
20/62
Storing Custom Objects
To store an item in view state, ASP.NET must be able toconvert it into a stream of bytes so that it can be added to
the hidden input field in the page. This process is called
serialization.
To make your objects serializable, you need to add a
Serializable attribute before your class declaration
Lp trnh Web 20
-
7/27/2019 04_StateManagement
21/62
Example:
Lp trnh Web 21
-
7/27/2019 04_StateManagement
22/62
Lp trnh Web 22
-
7/27/2019 04_StateManagement
23/62
Transferring Information Between
Pages
Cross-Page Posting
The Query String
Lp trnh Web23
-
7/27/2019 04_StateManagement
24/62
Cross-Page Posting
A cross-page postback is a technique that extends thepostback mechanism so that one page can send the user to
another page, complete with all the information for that
page.
To use cross-posting, you simply set PostBackUrl to the
name of another web form.
When the user clicks the button, the page will be posted
to that new URL with the values from all the input
controls on the current page.
Lp trnh Web 24
-
7/27/2019 04_StateManagement
25/62
Cross-Page Posting
Now if you load this page and click the button, the page will
be posted back to CrossPage2.aspx.
At this point, the CrossPage2.aspx page can interact with
CrossPage1.aspx using the Page.PreviousPage property
Lp trnh Web 25
-
7/27/2019 04_StateManagement
26/62
Getting More Information from the
Source Page
To get more specific details, such as control values, youneed to cast the PreviousPage reference to the appropriate
page class
Lp trnh Web 26
protected void Page_Load(object sender, EventArgs e){
CrossPage1 prevPage = PreviousPage as CrossPage1;
if (prevPage != null)
{ // (Read some information from the previous page.)
}
}
G tti M I f ti f th
-
7/27/2019 04_StateManagement
27/62
Getting More Information from the
Source Page
You can add the PreviousPageType directive to the .aspxpage that receives the cross-page postback.
The PreviousPage property will automatically use the
CrossPage1 type.
Lp trnh Web 27
G tti M I f ti f th
-
7/27/2019 04_StateManagement
28/62
Getting More Information from the
Source Page
You wont be able to directly access the control objects itcontains. Thats because the controls on the web page are
not publicly accessible to other classes. You can work
around this by using properties.
Lp trnh Web 28
public TextBox FirstNameTextBox
{
get { return txtFirstName; }
}
public TextBox LastNameTextBox{
get { return txtLastName; }
}
-
7/27/2019 04_StateManagement
29/62
Notes
The first time the second page accessesPage.PreviousPage, ASP.NET needs to create the
previous page object.
To do this, it actually starts the page processing but
interrupts it just before the PreRender stage, and it doesntlet the page render any HTML output.
However, this still has some interesting side effects. For
example, all the page events of the previous page are
fired, including Page.Load and Page.Init, and the
Button.Click event also fires for the button that triggered
the cross-page postback.
Lp trnh Web 29
-
7/27/2019 04_StateManagement
30/62
The Query String
Another common approach is to pass information using aquery string in the URL.
The query string is the portion of the URL after the
question mark.
The advantage of the query string is that its lightweight
and doesnt exert any kind of burden on the server.
Lp trnh Web 30
http://www.google.ca/search?q=organic+gardening
-
7/27/2019 04_StateManagement
31/62
The Query String
However, it also has several limitations: Information is limited to simple strings, which must contain
URL-legal characters.
Information is clearly visible to the user and to anyone elsewho cares to eavesdrop on the Internet.
The enterprising user might decide to modify the query
string and supply new values, which your program wontexpect and cant protect against.
Many browsers impose a limit on the length of a URL.
Lp trnh Web 31
-
7/27/2019 04_StateManagement
32/62
The Query String
To store information in the query string, you need to placeit there yourself
You can send multiple parameters as long as theyre
separated with an ampersand (&):
You can receive the values from the QueryString
dictionary collection exposed by the built-in Requestobject
Lp trnh Web 32
Response.Redirect("newpage.aspx?recordID=10");
Response.Redirect("newpage.aspx?recordID=10&mode=full");
string ID = Request.QueryString["recordID"];
-
7/27/2019 04_StateManagement
33/62
Notes
Informations in query string is always retrieved as astring.
Values in the QueryString collection are indexed by the
variable name. If you attempt to retrieve a value that isnt
present in the query string, youll get a null reference.
Unlike view state, information passed through the querystring is clearly visible and unencrypted. Dont use the
query string for information that needs to be hidden or
made tamperproof
Lp trnh Web 33
-
7/27/2019 04_StateManagement
34/62
A Query String Example
Reference: Beginning ASP.NET 3.5 in C sharp 2008 From Novice to
Professional, 2nd edittion, Apress (page 226228)
Lp trnh Web 34
-
7/27/2019 04_StateManagement
35/62
Cookies
Lp trnh Web35
-
7/27/2019 04_StateManagement
36/62
Cookies
Cookies provide another way that you can storeinformation for later use.
Cookies are small files that are created on the clients
hard drive.
Before you can use cookies, you should import the
System.Net namespace so you can easily work with theappropriate types.
Lp trnh Web 36
-
7/27/2019 04_StateManagement
37/62
Cookies
Both the Request and Response objects (which are
provided through Page properties) provide a Cookies
collection.
The important trick to remember is that you retrieve
cookies from the Request object, and you set cookies
using the Response object.
Lp trnh Web 37
-
7/27/2019 04_StateManagement
38/62
Cookies
A cookie added in this way will persist until the user
closes the browser and will be sent with every request. Tocreate a longer-lived cookie, you can set an expiration
date
Lp trnh Web 38
// Create the cookie object.
HttpCookie cookie = new HttpCookie("Preferences");
// Set a value in it.
cookie["LanguagePref"] = "English";
cookie["Country"] = "US";// Add it to the current web response.
Response.Cookies.Add(cookie);
cookie.Expires = DateTime.Now.AddYears(1);
-
7/27/2019 04_StateManagement
39/62
Cookies
You retrieve cookies by cookie name using theRequest.Cookies collection
Lp trnh Web 39
HttpCookie cookie = Request.Cookies["Preferences"];
string language;
if (cookie != null)
{
language = cookie["LanguagePref"];
}
-
7/27/2019 04_StateManagement
40/62
Cookies
The only way to remove a cookie is by replacing it with acookie that has an expiration date that has already passed
Lp trnh Web 40
HttpCookie cookie = new HttpCookie("LanguagePref");
cookie.Expires = DateTime.Now.AddDays(-1);Response.Cookies.Add(cookie);
-
7/27/2019 04_StateManagement
41/62
Example
Reference: Beginning ASP.NET 3.5 in C sharp 2008 From Novice to
Professional, 2nd edittion, Apress (page 230)
Lp trnh Web 41
-
7/27/2019 04_StateManagement
42/62
Session State
Session Tracking
Using Session State
Lp trnh Web42
-
7/27/2019 04_StateManagement
43/62
Session State
An application might need to store and access complexinformation such as custom data objects, which cant be
easily persisted to a cookie or sent through a query string.
Or the application might have stringent security
requirements that prevent it from storing information
about a client in view state or in a custom cookies.
In these situations, you can use ASP.NETs built-in
session state facility
Lp trnh Web 43
-
7/27/2019 04_StateManagement
44/62
Session State
Session state management is one of ASP.NETs premierefeatures. It allows you to store any type of data in
memory on the server.
The information is protected, because it is never
transmitted to the client, and its uniquely bound to a
specific session
Lp trnh Web 44
-
7/27/2019 04_StateManagement
45/62
Session Tracking
ASP.NET tracks each session using a unique 120-bitidentifier. (ASP.NET uses a proprietary algorithm to
generate this value).
This ID is the only piece of session-related information
that is transmitted between the web server and the client.
When the client presents the session ID, ASP.NET looksup the corresponding session, retrieves the objects you
stored previously, and places them into a special
collection so they can be accessed in your code
Lp trnh Web 45
-
7/27/2019 04_StateManagement
46/62
Session Tracking
For this system to work, the client must present theappropriate session ID with each request.
You can accomplish this in two ways:
Using cookies: In this case, the session ID is transmitted in a
special cookie (named ASP.NET_SessionId), which
ASP.NET creates automatically when the session collection
is used.
Using modified URLs:In this case, the session ID istransmitted in a specially modified (ormunged) URL.
Lp trnh Web 46
-
7/27/2019 04_StateManagement
47/62
Notes
Session state forces the server to store additional
information in memory.
A careless use of session state is one of the most common
reasons that a web application cant scale to serve a large
number of clients
Lp trnh Web 47
-
7/27/2019 04_StateManagement
48/62
Using Session State
You can interact with session state using theSystem.Web.SessionState.HttpSessionState class, which
is provided in an ASP.NET web page as the built-in
Session object.
The syntax for adding items to the collection and
retrieving them is basically the same as for adding items
to a pages view state.
Lp trnh Web 48
Session["InfoDataSet"] = dsInfo;
dsInfo = (DataSet)Session["InfoDataSet"];
-
7/27/2019 04_StateManagement
49/62
Using Session State
Session state can be lost in several ways: If the user closes and restarts the browser.
If the user accesses the same page through a different
browser window, although the session will still exist if aweb page is accessed through the original browser window.
Browsers differ on how they handle this situation
If the session times out due to inactivity.
If your web page code ends the session by calling the
Session.Abandon() method.
Lp trnh Web 49
-
7/27/2019 04_StateManagement
50/62
HttpSessionState Members
Member Description
IsCookielessIdentifies whether the session is tracked with a cookie
or modified URLs
IsNewSession
Identifies whether the session was created only for
the current request
ModeProvides an enumerated value that explains how
ASP.NET stores session state information
SessionIDProvides a string with the unique session identifier for
the current client
TimeoutDetermines the number of minutes that will elapse
before the current session is abandoned.
Lp trnh Web 50
-
7/27/2019 04_StateManagement
51/62
HttpSessionState Members
Member Description
Abandon()Cancels the current session immediately and
releases all the memory it occupied.
Clear()Removes all the session items but doesnt change
the current session identifier
Lp trnh Web 51
-
7/27/2019 04_StateManagement
52/62
A Session State Example
Reference: Beginning ASP.NET 3.5 in C sharp 2008 From Novice to
Professional, 2nd edittion, Apress (page 233)
Lp trnh Web 52
-
7/27/2019 04_StateManagement
53/62
Session State Configuration
Cookieless
TimeoutMode
Lp trnh Web53
-
7/27/2019 04_StateManagement
54/62
Session State Configuration
You configure session state through the web.config filefor your current application
Lp trnh Web 54
-
7/27/2019 04_StateManagement
55/62
Cookieless
You can set the cookieless setting to one of the valuesdefined by the HttpCookieMode enumeration, as
described in Table below
Lp trnh Web 55
Value Description
UseCookies
Cookies are always used, even if the browser or device
doesnt support
cookies or they are disabled
UseUriCookies are never used, regardless of the capabilities of the
browser or device. Instead, the session ID is stored in the URL
UseDeviceProfileASP.NET chooses whether to use cookieless sessions by
examining the BrowserCapabilities object.
AutoDetect
ASP.NET attempts to determine whether the browser supports
cookies by attempting to set and retrieve a cookie (a technique
commonly used on the Web)
-
7/27/2019 04_StateManagement
56/62
Timeout
This specifies the number of minutes that ASP.NET willwait, without receiving a request, before it abandons the
session.
You can also programmatically change the session
timeout in code
Lp trnh Web 56
Session.Timeout = 10;
-
7/27/2019 04_StateManagement
57/62
Mode
The remaining session state settings allow you toconfigure ASP.NET to use different session state services,
depending on the mode that you choose.
InProc
Off
StateServer
SQLServer
Custom
Lp trnh Web 57
-
7/27/2019 04_StateManagement
58/62
Application State
Lp trnh Web58
-
7/27/2019 04_StateManagement
59/62
Application State
Application state allows you to store global objects thatcan be accessed by any client
Application state is based on the
System.Web.HttpApplicationState class, which is
provided in all web pages through the built-in Applicationobject.
Application state is similar to session state
Lp trnh Web 59
-
7/27/2019 04_StateManagement
60/62
Lp trnh Web 60
-
7/27/2019 04_StateManagement
61/62
you need to use the Lock() and Unlock() methods, whichexplicitly allow only one client to access the Application
state collection at a time
Lp trnh Web 61
-
7/27/2019 04_StateManagement
62/62
An Overview of State
Management Choices