top of page
Writer's pictureThe Tech Platform

ASP.NET State Management

Updated: Mar 18, 2023



ASP.NET is a popular web development framework that allows developers to build dynamic web applications using the .NET platform. State management is a crucial aspect of web development, as it involves storing and managing data that is required by an application. In ASP.NET, there are several approaches to state management, each with its own advantages and limitations. In this article, we will explore the different approaches to state management in ASP.NET in detail.


Why State Management

State management is an essential aspect of web development, including in ASP.NET. In ASP.NET, state management refers to the process of storing and managing data that is required by an application. There are several reasons why we need state management in ASP.NET:

  1. Maintaining state across requests: ASP.NET is a stateless framework, meaning that it does not maintain a state between requests. State management techniques, such as cookies, session state, and view state, enable developers to maintain state across requests, allowing the application to remember user preferences, maintain user authentication, and provide a personalized experience to the user.

  2. Performance optimization: State management can help optimize application performance by reducing the amount of data that needs to be fetched from the database or regenerated. Caching frequently used data in memory can improve response times and reduce the load on the database.

  3. User personalization: State management enables developers to store user-specific data, such as user preferences, settings, and past interactions, to personalize the user experience. For example, an e-commerce website can use state management to remember a user's shopping cart contents, wishlist items, and purchase history.

  4. Scalability: State management can help improve application scalability by reducing the amount of data that needs to be fetched from the database or regenerated. By storing frequently accessed data in memory, caching can reduce the load on the database and improve application performance.

  5. Security: State management can help improve application security by providing a mechanism for storing and encrypting sensitive data, such as user authentication information and user-specific data.


State Management Techniques



Client Side State Management

In client-side state management, the resultant information out of state management is 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 the 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 that carry a lot of information.


1. 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 requested 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 in 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 for the cookie. A cookie can be read 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 add it to the Cookies collection. It can be read as follows.

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 follows.

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


2. 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 a small amount of information. (Otherwise, it can slow down the application if you store a lot of information in the 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 that 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.


3. Control State

The 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 this case, it is a good idea to keep the state of the controls in control state (which cannot be disabled by the user).


4. Query String

The query string is a text string that 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 the name and number of times from the URL query string.

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


5. 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 when you want to store the page information in the page itself when a variable’s value frequently changes when HTTP post is used. But they’re easy for malicious users to manipulate.

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

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


6. 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 any more 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).


1. Application State

Application state is a global storage mechanism that can be accessed from all pages of a web application. It can be 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 the 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 follows.

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.


2. 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 website. 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 cast 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.


3. 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>

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 );


4. DB Support

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


Advantages of state management in ASP.NET core:

  1. Improved performance: Using state management techniques like caching, developers can improve the performance of their ASP.NET core applications. By storing frequently accessed data in memory, caching can reduce the number of times data needs to be regenerated, resulting in faster response times.

  2. User personalization: State management techniques like cookies and session state allow developers to store user-specific data, such as login information or user preferences. This can be useful for creating personalized experiences for users.

  3. Scalability: ASP.NET core provides several approaches to state management, each with its own advantages and limitations. By understanding the different approaches to state management, developers can choose the most appropriate approach for their specific application requirements, which can help improve scalability.

  4. Security: ASP.NET core provides built-in security features, such as data encryption, to help protect sensitive data that is stored in state management techniques like cookies and session state.

Disadvantages of state management in ASP.NET core:

  1. Performance overhead: Storing data in state management techniques like session state and cookies can cause performance overhead, especially if large amounts of data are being stored. This can result in slower response times and decreased application performance.

  2. Increased memory usage: State management techniques like caching can increase the amount of memory used by an application. This can be a problem for applications that run on shared hosting environments or on systems with limited memory.

  3. Security risks: State management techniques like cookies and session state can be vulnerable to security risks, such as session hijacking or cross-site scripting attacks, if not implemented properly. Developers need to be aware of these risks and take steps to mitigate them.

  4. Maintenance overhead: Managing the state of an application can be complex and can require additional effort and resources from developers. This can increase maintenance overhead and make it harder to maintain and update the application over time.

Conclusion

State management is an essential aspect of ASP.NET development. It enables developers to maintain state across requests, optimize performance, personalize the user experience, improve scalability, and enhance application security. By understanding the different state management techniques available in ASP.NET and choosing the appropriate ones for their application, developers can create robust and scalable web applications that provide a great user experience.

0 comments

Comments


bottom of page