Almost every web application today need to store some information about a user to use later, for example a authentication token, theme name, or language. One thing to remember is not to store sensitive information on the client, like credit card numbers or bank information, even thou you can enable encryption on view state it is not as secure as storing that type of information on the server.
ASP.NET provides five ways of storing user information on the client. The five ways are:
- View state
- Control state
- Hidden fields
- Cookies
- Query string
View State
View state is a mechanism used in ASP.NET to store user-specific request and response data between page requests. The information in the view state is sent back to the user with the response of the page. When the user makes the next request the view state is returned with the request.
When the page is processed it pulls the view state data from the request and use it reset properties on the page and controls. View state is always enabled as a part on every ASP.NET page. The Page.ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This object is of the type StateBag.
When a page is requested by the user the current state of the page and it’s controls is hashed into a string and saved in the page as an HTML hidden field called __VIEWSTATE. If data is to long for a single field (based on the value of the Page.MaxPageStateFieldLength property), ASP.NET performs a view state chunking to split it across multiple hidden fields. In the HTML response the view state hidden field looks like this.
As you can se the value in __VIEWSTATE is hashed, compressed and encoded for Unicode implimentations, this is to be a bit more secure and provide better performance.
When using view state you need to consider the security in using it. As said in the previous sentence, the view state is hashed, it also includes a message authentication code (MAC). This MAC is used by ASP.NET to determine if the view state data sent by the client have been tampered with. Do not mistake this as fully encrypted data, it is not. But for the most part it helps ensure security in many situations.
If you do store sensitive data in the view state, you would want to enable encryption on the view state. To do so you use the Page.ViewStateEncryptionMode property. This will secure the view state but also have a big impact on performance on the server, both CPU for encryption/decryption and bandwidth for the server and client because the view state sent between the two is much bigger.
To enable view state on the entire site you can set the following in the web.config.
If you want to set encryption on single pages you can do this in the @ page directive on each page.
Disabling View State Date
View state is enabled by default for all the controls in your pages. This includes controls such as Literal and Label, that you might never need to include as part of the view state. It is a best practice to have view state enabled on as few controls as possible, this is because it minimize the amount of data sent back and forth between the client and server.
You can control the view state on the page level by enabling and disabling Page.EnableViewState and Page.ViewStateMode, for controls you can use Control.EnableViewState and Control.ViewStateMode.
The ViewStateMode is new in .NET Framework 4. The ViewStateMode property of a page or control has an effect only if EnableViewState is true. By default Page.EnableViewState is Enabled and Control.ViewStateMode is Inherited, which causes the control to use the page’s view state. There for if you do not change ViewStateMode, EnableViewState controls it entirely.
If you set EnableViewState to false, view state is disabled for the page or control, regardles of the value of ViewStateMode. If EnableViewState is set to true, you can set ViewStateMode to disable view state. Because ViewStateMode can inherit the page’s setting, you should always leave EnableViewState set to true and use ViewStateMode to control view state.
To disable view state for all controls on a page, simply set Page.ViewStateMode to Disabled. You can then selectively re-enable view state for specific controls by setting each control’s ViewStateMode property to Enable. Essentially, ViewStateMode allows you to opt in to view state, whereas EnableViewState requires you to opt out.
You can also disable view state for the entire website by setting enableViewState in the web.config file.
Custom View State
You can use the this.ViewState dictionary collection to read and write your own view state data. Adding data to the view state in this way is a efficient and secure way of storing data between requests. The view state is only stored for the same page, so this method of storing user data is only usable for storing temporary data for a single page. Below is a example of reading and writing your own view state data.
The result of the example looks like this;
and after the Submit button was clicked;
Hidden Fields
Hidden fields in HTML are simply input fields that are embedded in the page’s HTML, not displayed for the user. ASP.NET provides a control that lets you create your own custom hidden fields in a manner similar to how you create other controls. The HiddenField control allows you to store a store data in its Value property. You can add a HiddenField control to you page by using the following code in you markup.
To programmatically set the Value property of the HiddenField1 you do the following.
When viewing the HTML source of the page this is what you see.
What differentiate hidden fields from view state is that it is not encrypted, hashed or chunked and the user can view and modify the value.
Cookies
A cookie is a small amount of data that you write to the client to be stored and then passed with requests to your site. You write persistent cookies to a text file on the client machine. These cookies are meant to survive even if the user shuts down the browser and reopens it at a later time. You can also write temporary cookies that survive as long as the browser not shuts down because they are stored in the browsers memory. These cookies are used only during the current web session.
The mechanism that client and server use to create cookies is as follows.
- The client requests a page.
- The server responds with the HTML and a cookie
- The client request another page, and also sends the cookie in the request.
Cookies are a simple and reliable way of storing data on the client. However the client can delete a cookie at any time. No matter what expiration date the server have set.
Reading and Writing Cookies
A web application creates a cookie by sending it to the client as a header in an HTTP response. The following example shows how to read and write a cookie.
This checks to see if the cookie object exists in the Page.Request.Cookeis collection, if it exists, it writes the value otherwise it writes First time visitor. Then it sets the value of the lastVisit cookie, and set the Expires property to the next day.
If you do not set the Expires property the cookie is stored in the client’s browser memory and is removed when the browser shuts down. You can also create a cookie by using the Page.Response.Cookies.Add() method, which takes a HttpCookie object as a argument.
By default a browser do not send a cookie for a host to a website with a different host, this is a security feature. You also have control over the scope of the cookies. You can limit it to a specific directory on you web server or expand the scope to the entire domain. The scope of the cookie determines which pages have access to the cookie. To limit the scope of a cookie to a directory you specify the Path property of the HttpCookie class. For example,
This will limit the cookie so that it is only sent with the request in pages in the /MyApplication directory on the server.
To expand the scope of a cookie to the entire domain you specify the Domain property of the HttpCookie class.
Setting the Domain property will cause the cookie to be sent to all pages of the domain. It will also be sent with request to pages hosted on any subdomain of the domain specify. In the previous example that would mean the cookie would also be sent to www.frejnorling.com, private.frejnorling.com and so on.
Storing Multiple Values in a Single Cookie
The size of your cookie is dependent on the browser. Each cookie can be up to 4 KB in length. In addition, you can typically store up to 20 cookies per site. If you need to work around the 20-cookie limit, ASP.NET let you store multiple values in a single cookie by setting the cookie’s name and its key value. The following shows a example.
As you can se the property Expires is set just once for all values, this is because all values are stored in a single cookie on the client. When the client requests a page the server sends the following Set-Cookie header in the response back.
This will then be sent with every request made from the client, and the server will parse the string and populate the HttpCookieCollection accordingly.
You can not delete a cookie from the client, but you can change its Expires property to null. That will make the browser delete the cookie from the client when the browser shuts down.
Query Strings
So query strings, there is not that much to say about them that have not been said before. But you give you a short summery of them anyway.
Query strings are set off from the URL with a question mark (?) followed by the query string term, or parameter name, an equal sign (=) and the value. You can append multiple query string parameters by using the ampersand (&). A typical query string might look like this
http://www.frejnorling.com?lang=en&theme=blue&q=hello+world
Values sent to your page via query string can be retrived on the server through the Page.Request.QueryString property.
To access the lang parameter in the example URL above you write the following.
Request.QueryString[“lang”];
There is a browser length limitation on query string, the maximum length of a query string is 2083 characters long. But if you want to send a URL link in a mail, you would use a maximum of 70 characters for the URL.
To add a query string value to your site, you need to manually append it to the hyperlink.