ASP.NET State Management

Daneesha Bartholomeusz
7 min readAug 28, 2021

State management might appear as something new and big but it’s actually very similar to what we have used so far. For example session state or application state is an object. A cookie is a small file that we write to the file system.

There’re individual features about all of the state management techniques. We have to keep them in mind in order to give a solution to a state management problem. (It’s our call to decide which state management techniques we use).

What is State Management

So what is a state. It is the state of the application at the given time. For example this can include who are the users logged in to the application, how many page hits are there, what is the information the users have entered into the inputs of the application etc.

Why State Management

Why do we need state management. Web applications are stateless. That means they don’t maintain a state. A new page is created for each page request. Each request is treated as an independent request.

And also client-server communication is disconnected. (Client and the server are not permanently connected).

There isn’t anywhere to store the state details of an application. That’s why we need a state management mechanism, to store the state of the application, to store data during roundtrips. (A roundtrip is a call from the client to the server again coming back to the client).

State Management Techniques

We can classify state management as above. State management can be either client side or server side. This is based on the fact where you store your data, data that comes as a result of state management. (Client is the machine on which the browser runs and the server is the machine where the application is hosted).

(I referred several articles in preparation for this discussion. They do the classification slightly differently to each other. Caching is included as a state management technique in one place in MS Docs but not in another. DB Support is something I came across in a MS Docs article but not in other articles. )

Client Side State Management

In client side state management the resultant information out of state management in stored in the client machine. This has the benefit of not taking up any server resources. But has the drawbacks of having minimal security and a limit on information you store as such. There’s a limit on information in the sense that there is a limit on how much information you can send to the client or store on the client, because too much information can slow down the application and reduce performance. In another sense firewalls can block applications which carry a lot of information.

Cookies

A cookie is a small file. It is written to the user’s file system. It is sent to the server along with the request information so that the server can process it. Cookies are commonly used for personalization. (Personalization is changing the application so that the user feels that it’s tailored for him or her). It is best used when there’re small amounts of information, to store them temporarily and the information is non-sensitive.

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

A cookie can be written as above. A cookie as some other state management techniques, is a name value pair. You can set a value by writing the key within square brackets. You can set an expiration time to the cookie. A cookie can be read as below. Here we’re reading the cookie value and displaying it on a label.

if (Request.Cookies["userName"] != null)lblName.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

We check if the cookie is not null before we read it. Otherwise it throws an exception. We “Server.HtmlEncode” the read line so that we can evade added scripts by malicious users.

A cookie can be written as below also.

HttpCookie aCookie = new HttpCookie("lastVisit");aCookie.Value = DateTime.Now.ToString();aCookie.Expires = DateTime.Now.AddDays(1);Response.Cookies.Add(aCookie);

Here we construct it as a HttpCookie object and adding it to the Cookies collection. It can be read as following.

if (Request.Cookies["lastVisit"] != null){    HttpCookie aCookie1 = Request.Cookies["lastVisit"];    lblName.Text = Server.HtmlEncode(aCookie1.Value);}

The cookie is read and stored in an object. Then it is displayed on a label.

You can write multiple values to the same cookie. Here’s an example.

Response.Cookies["userInfo"]["userName"] = "daneesha";Response.Cookies["userInfo"]["lastVisit"] = DateTime.Now.ToString();Response.Cookies["userInfo"].Expires = DateTime.Now.AddDays(1);

It can be read as following.

lblName.Text = 
Server.HtmlEncode(Request.Cookies["userInfo"] ["userName"]);

View State

View state is a dictionary object. It is used for page level state maintenance. View state is stored in hidden field/s. It’s good to be used when there is small amount of information. (Otherwise it can slow down the application if you store a lot of information in view state).

protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ViewState["count"] != null)
{
ViewState["count"] =
Convert.ToInt32(ViewState["count"]) + 1;
}
else
{
ViewState["count"] = "1";
}
}
}

Here we’re writing a counter which increments as the value in the view state is incremented. It can be used with a method as the following.

protected void btnSubmit_Click(object sender, EventArgs e)
{
lblCount.Text = ViewState["count"].ToString();
}

As the user clicks the button the counter keeps counting and incrementing the value that is displayed on the label to the user.

Control State

Control state is all about controls. It preserves the state of the controls on a web page. The value of it is written in hidden field/s. If the user disables the view state (which is possible) the controls on your page might not be able to function correctly. In which case it is a good idea to keep the state of the controls in control state (which cannot be disabled by the user).

Query String

Query string is a text string which is appended to the URL. It is separated from the URL by a question mark and multiple values can be added after an ampersand. It can be used in situations where security is not a concern, to transfer information from page to page, using HTTP GET.

Here’s an example taken from MS Docs’ MVC tutorial.

public string Welcome(string name, int numTimes = 1) 
{
return HttpUtility.HtmlEncode("Hello " + name + ",
NumTimes is: " + numTimes);
}

The welcome action method in the HelloWorld controller picks up the values for name and number of times from the URL query string.

http://localhost:xxxx/HelloWorld/Welcome?name=Scott&numtimes=4

Hidden Fields

Hidden fields are just like any other control, the only thing is they don’t appear on the browser. They can be used in situations where you want to store the page information in the page itself, when a variable’s value changes frequently, when http post is used. But they’re easy for malicious users to manipulate.

<input type="text" id="txtCustomerNumber" hidden/>

Above is an example for a hidden field. It has the hidden attribute appended to it.

Caching

There’re two forms of caching. Application caching, which is caching of the data that you generate, and page output caching, which is caching of the output of page processing. (I will not go into anymore detail because space doesn’t allow me to explain sufficiently about caching).

Server Side State Management

In server side state management, the output of state management is stored in the server machine. (In the server’s memory).

Application State

Application state is a global storage mechanism that can be accessed from all pages of a web application. It can used when there’re infrequent changes, using global information (not specific to a client), when security is not an issue, and data is in small quantities. It is fast.

There’re two events in the Global.asax file pertaining to application state.

protected void Application_Start(object sender, EventArgs e)
{
Application["AppstartMessage"] = "Hello";
}
protected void Application_End(object sender, EventArgs e)
{
Application["AppEndMessage"] = "Application Closed";
}

The above set messages can be used as following.

protected void Page_Load(object sender, EventArgs e)
{
lblWelcome.Text = (string)Application["AppstartMessage"];
}

You need to cast it to the appropriate type before you use it as the application state returns an object.

Session State

session state maintains the current browser session. A session starts when a user requests a page and ends when the user closes the browser or leaves a web site. This can be used for short lived, sensitive data, specific to a session and comes in small amounts.

protected void btnSubmit_Click(object sender, EventArgs e)
{
Session["UserName"] = txtFirstName.Text;
Response.Redirect("Home.aspx");
}

Above we’re writing a value to the session and then redirecting to another page.

Then we can use the value in the session as shown below. It has to be appropriately casted before being used.

protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = (string)Session["UserName"];
}

There’re two events mentioned in the Global.asax file.

protected void Session_Start(object sender, EventArgs e)
{
Response.Write("Session_Start");
}
protected void Session_End(object sender, EventArgs e)
{
Response.Write("Session_End");
}

You can store other data types in sessions objects as well. (And indeed in other state management mechanisms). Here’s how to store an ArrayList in a session.

ArrayList initialStocks = new ArrayList();
initialStocks.Add(10);
initialStocks.Add(12.35);
initialStocks.Add(15.40);
Session["StockPrices"] = initialStocks;ArrayList stockPrices = (ArrayList)Session["StockPrices"];

There’re several session state modes.

  1. In proc — in “in process” mode the session information is stored in the server’s memory.
  2. State server — in this mode the information is stored in another process called the ASP.NET state service.
  3. In SQL Server mode the info is stored in a SQL Server database.
  4. In Custom mode a custom storage mechanism can be specified.
  5. Off mode — when the session state is disabled.

Profile Properties

Profile properties use ASP.NET profiles. The data thus stored is not lost when the session expires. You can write to a DB, an XML file or a web service. You can use this method to store user specific information that persists.

Here’s how to set the profile. (In web.config file).

<profile>
<properties>
<add name="CustomerCode" />
</properties>
</profile>

The property CustomerCode can be assigned like this with the value taken from the user through an input control.

Profile.CustomerCode = txtCustomerCode.Text;

It can be used in a method like this.

customerInfo = GetCustomerInfo( Profile.CustomerCode );

DB Support

DB support comes with a lot of security, can be used for personalization purposes, and when consistency needs to be maintained, and for data mining purposes. It is good when large amounts of data needs to be dealt with, there’re transactions present, when the data needs to survive over restarts.

--

--