State Management ASP.NET

Mirza Farrukh Ali
7 min readOct 6, 2017

Without State Management in ASP.NET , typically all information associated with the page and the controls on the page would be lost with each round trip . For example, if a user enters information into a form, that information would be lost in the round trip.

ASP.NET includes below features that help you preserve data on both a per-page basis and an application-wide basis.

  • View state
  • Control state
  • Hidden fields
  • Cookies
  • Query strings
  • Application state
  • Session state

ViewState: When the HTML markup for the page is rendered, the current state of the page and values that must be retained during postback are serialized into base64-encoded strings. This information is then put into the view state hidden field or fields.

When page is submitted to the server, the state of the controls is encoded and sent to the server at every form submission in a hidden field known as __VIEWSTATE. The server sends back the variable so that when the page is re-rendered, the controls render at their last state, so no extra programming is needed.

<input type=”hidden” name=”__VIEWSTATE” id=”__VIEWSTATE” value=”/wEPDwUKMTkwNjc4NTIwMWRkL5PbikezkXhkI2kmrh3VUjVDGoU=” />

// Save PageArrayList before the page is rendered. save custom value to viewstate
ViewState.Add(“arrayListInViewState”, PageArrayList);

arrayList = (ArrayList)ViewState[“arrayListInViewState”]; getting value

ViewState Security:

By default, view state data is stored in the page in a hidden field and is encoded using base64 encoding. In addition, a hash of the view state data is created from the data by using a machine authentication code (MAC) key. The hash value is added to the encoded view state data and the resulting string is stored in the page. When the page is posted back to the server, the ASP.NET page framework re-computes the hash value and compares it with the value stored in view state. If the hash values do not match, an exception is raised that indicates that view state data might be invalid.But, ASP.NET page framework cannot test whether viewdata is read by malicious users. You can only prevent people from viewing this data in two ways: by transmitting the page over SSL, and by encrypting the view state data.

Advantages are no server resources are required and Enhanced security features as it is hashed, compressed, and encoded for Unicode implementations.

Disadvantages are:
Performance considerations as storing large values can cause the page to slow down and Potential security risks as value can be seen if the page output source is viewed directly, creating a potential security issue.

Control State:

use Control State when creating custom control rather than using Page ViewState, because if Page ViewState is disabled by developer it would break your control whereas Control State cannot be disabled.

protected override void OnInit(EventArgs e){

base.OnInit(e);

Page.RegisterRequiresControlState(this);

}

protected override object SaveControlState(){

object state = base.SaveControlState();

return new Pair(state, _addressInfo);

}

protected override void LoadControlState(object savedState){

_addressInfo = new AddressInfo();

Pair pair = (Pair) savedState;

_addressInfo = (AddressInfo) pair.Second;

base.LoadControlState(pair.First);

}

Hidden fields:

The hidden field is a control that stores a value but does not display that value to the user. ASP.NET also defines an event called ValueChanged for the HiddenFieldcontrol. This fires on postback when the Value property of the control is different from the previous posting. The event does not cause a postback itself, and unlike most nonpostback controls, the HiddenField does not expose an AutoPostBack property to force an instantaneous postback. As with all nonpostback controls (explained in Chapter 3), notification of the event will be cached until the form is posted back by some other control, at which point the event will be raised in server code.

<input type="hidden" id="FormStatus" value="Draft Saved">

Disadvantages are Potential security risks, Performance considerations and Storage limitations.

Cookies:

If a user requests a page from your site and your application sends not just a page, but also a cookie containing the date and time, when the user’s browser gets the page, the browser also gets the cookie, which it stores in a folder on the user’s hard disk.
Later, if user requests a page from your site again, when the user enters the URL the browser looks on the local hard disk for a cookie associated with the URL. If the cookie exists, the browser sends the cookie to your site along with the page request. Your application can then determine the date and time that the user last visited the site. You might use the information to display a message to the user or check an expiration date.

Example:A site that asks a user to log on might use a cookie to record that the user already logged on so that the user does not have to keep entering credentials.

Most browsers support cookies of up to 4096 bytes and allow only 20 cookies per site.

Response.Cookies["userName"].Value = "patrick";
Response.Cookies["userName"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("lastVisit");
aCookie.Value = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
//also more than one value cookie
Response.Cookies["userInfo"]["userName"] = "patrick";
Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();
Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

you can set the scope of cookies in two ways:

  • Limit the scope of cookies to a folder on the server, which allows you to limit cookies to an application on the site.www.contoso.com/App/
appCookie.Path = "/Application1";
  • Set scope to a domain, which allows you to specify which subdomains in a domain can access a cookie.
appCookie.Domain = "support.contoso.com";
HttpCookie aCookie = Request.Cookies["userName"];
Label1.Text = Server.HtmlEncode(aCookie.Value);

You should never store sensitive data in a cookie.

Users can set their browser to refuse cookies. No error is raised if a cookie cannot be written. One way to determine whether cookies are accepted is by trying to write a cookie and then trying to read it back again. If you cannot read the cookie you wrote, you assume that cookies are turned off in the browser.

Cookies and Session State:

ASP.NET must track a session ID for each user so that it can map the user to session state information on the server. By default, ASP.NET uses a non-persistent cookie to store the session state. However, if a user has disabled cookies on the browser, session state information cannot be stored in a cookie.ASP.NET offers an alternative by configuring your application to store session IDs not in a cookie, but in the URLs of pages in your site. However, under some limited circumstances, if the user shares the URL with someone else — perhaps to send the URL to a colleague while the user’s session is still active — then both users can end up sharing the same session, with unpredictable results.

Disadvantages are Size limitations ,User-configured refusal and Potential security risks.

QueryString:

You often need to pass parameters from one page to another. To give the destination page enough information so that it can determine the correct action for each request, parameters may be submitted.For ASP.NET applications, parameters are appended to the destination document’s URL. Immediately after the URL, a ? character is added to indicate that there are indeed parameters. Then for each parameter, there is a name and a value, such as “Flavor=Chocolate”. Each parameter must be separated by a & character.

<a href="Process.aspx?Name=Sam&Address=123%20Main%20Street">Sam</a>

Disadvantages are Limited capacity as Some browsers impose a 2083-character limit on the length of URLs and Potential security risk.

Application state:

when users are working with more complicated objects in application state — such as collections — concurrent access to items stored in application state can result in deadlocks, race conditions, and access violations.For that, you can force access to items in application state to take place in an orderly manner by using two methods of the application state object: Lock and Unlock.

Application.Lock();
Application[Request.Browser.Browser]+=1
Application.UnLock();

Disadvantages are Application scope as variables stored in application state are global only to the particular process the application is running in, and each application process can have different values,Limited durability of data as its lost if the Web server process containing it is destroyed, such as from a server crash, upgrade, or shutdown and Resource requirements as state requires server memory.

Session state:

ASP.NET session state identifies requests from the same browser during a limited time window as a session, and provides a way to persist variable values for the duration of that session. Session variables are stored in a SessionStateItemCollection object that is exposed through the HttpContext.Session property.
Session[“FirstName”] = FirstNameTextBox.Text;
ArrayList stockPicks = (ArrayList)Session[“StockPicks”];

Sessions are identified by a unique identifier that can be read by using the SessionID property. A session is considered active as long as requests continue to be made with the same SessionID value. If the time between requests for a particular session exceeds the specified time-out value in minutes, the session is considered expired. Requests made with an expired SessionID value result in a new session.

ASP.NET maintains cookieless session state by automatically inserting a unique session ID into the page’s URL
http://www.example.com/(S(lit3py55t21z5v55vlm25s55))/orderform.aspx

When ASP.NET sends a page to the browser, it modifies any links in the page that use an application-relative path by embedding a session ID value in the links. (Links with absolute paths are not modified.) Session state is maintained as long as the user clicks links that have been modified in this manner.

Session state modes:

  • InProc mode, which stores session state in memory on the Web server. This is the default
  • StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm. To use StateServer mode in a Web farm, you must have the same encryption keys specified in the machineKey element of your Web configuration for all applications that are part of the Web farm.
<configuration>
<system.web>
<sessionState mode="StateServer"
stateConnectionString="tcpip=SampleStateServer:42424"
cookieless="false"
timeout="20"/>
</system.web>
</configuration>
  • SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
<configuration>
<system.web>
<sessionState mode="SQLServer"
sqlConnectionString="Integrated Security=SSPI;data
source=SampleSqlServer;" />
</system.web>
</configuration>
  • Custom mode, which enables you to specify a custom storage provider.
  • Off mode, which disables session state.

Disadvantages are Performance considerations as variables that contain blocks of information, such as large datasets, can adversely affect Web-server performance as server load increases.

--

--