Asp.Net state management tutorials

This asp.net tutorial, we will discuss various asp.net state management techniques. We will discuss cookies, session, view state, query string, Cookieless session in Asp.Net, etc.

View state in Asp.Net

Let us first discuss on view state in Asp.Net.

  • View state is one of the popular and simple state management techniques.
  • View state uses a hidden field that ASP.NET automatically inserts in the final, rendered HTML of a web page.
  • It is very much helpful to store information that is used for multiple postbacks in a single web page.
  • We can enable and disable view state at the control level as well as page level.
  • You can use the EnableViewState= “True/False”; to enable or disable ViewState for control level or page level.

Example to store value:

ViewState["UserName"] = "AspDotNetHelp";

To retrive the value we can write like this:

string currentUserName = ViewState["UserName"].ToString();

But the view state data is not secure, because Asp.Net uses a Base64 string.

But if your view state data contains secret data then you can encrypt that data by using ViewStateEncryptionMode property at page level or application level like below:

Page Level:

<%@Page ViewStateEncryptionMode="Always" %>

Website level:

<configuration>
<system.web>
<pages viewStateEncryptionMode="Always" />
</system.web>
</configuration>

This is how we can use view state in asp.net.

Query String in Asp.Net

Like view state and cross-page posting, the asp.net query string is also a state management technique. This helps us to send data from one page to another page.

Here the data will be sent through the browser URL.

Example:
Below is a way to send the data to a different page.

Response.Redirect("ArticleDetails.aspx?ArticleID=1");

Similarly below is a ways, we can retrieve the query string data:

string articleID = Request.QueryString["ArticleID"];

We can also send multiple parameters by using query string in asp.net like below:

Response.Redirect("ArticleDetails.aspx?ArticleID=10&Category=Asp.Net");

The query string is very much lightweight, so there will be very less burden on the server. But there are few limitations in this also:

Limitations of Query String in Asp.Net

  • Information is limited to simple strings, which must contain URL-legal characters since its passed through browser url.
  • Information is clearly visible to the user and to anyone can trap the values.
  • The user also can modify the value and can send the new values to the server.
  • Most of the browser has a limitation on the length of the url (1 KB to 2KB), so we can not send a large amount of data.

Cookies in asp.net

Now, we will see what is a cookie, as well as the types of cookies available in asp.net.

A cookie can be defined as the small amount of memory used by the web server within the client system.

The cookie is requested to maintain the personal information of the client. Information like username, no of visits, last visited date etc are get stored.

There are 2 types of cookies:

  • In memory cookie
  • Persistent cookie

In memory Cookie in asp.net

When the cookie is maintained within the browser process memory then it is called an in-memory cookie. This is very much temporary which will be erased when the browser is closed.

Create cookie in asp.net

HttpCookie obj = new HttpCookie("nameofcookie”);
obj.Value = "100”;
Response.AppendCookie(obj); //Here cookie will be send to the browser.

Reading cookie in asp.net

HttpCookie obj;
obj = Request.Cookies["nameofcookie”];
if(obj !=null)
{
string value = obj.Value; //This will return the value.
}

Persistent cookie in asp.net

  • When the browser maintains cookie on to harddisk memory then it is called a persistent cookie.
  • This will have a lifetime when the cookie will erase.

Create cookie in asp.net

HttpCookie obj = new HttpCookie("nameofcookie”);
obj.Value = "100”;
obj.Expires.AddDays(5);//Cookie will expire after 5 days
Response.AppendCookie(obj);

Reading cookie in asp.net

HttpCookie obj;
obj = Request.Cookies["nameofcookie”];
if(obj !=null)
{
string value = obj.Value; //This will return the value.
}

This is how we can use cookie in asp.net.

Session management in Asp.Net

Now we will discuss session state state management technique in asp.net.

Through cookies or query string it is very difficult to store and access complex information like custom data objects.

Session 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. Every client that accesses the application has a different session.

Most of the eCommerce site uses session mechanism in asp.net.

ASP.NET tracks each session using a unique 120-bit identifier. That is known as sessionid which is transmitted between the web server and the client.

Below is the syntax to store value in Session in Asp.Net

Session["UserName"] = "Your User Name";

Below is the way to retrieve value from the session in Asp.Net.

if (Session["UserID"] != null)
{
string userName = Session["UserID"].ToString();
}

The session id is submitted through a cookie name as ASP.NET_SessionId. Or a Session ID is transmitted in a specially modified URL. This is used in the case where the client does not support cookies.

Session state is global to your entire application for the current user.
It stores in the server memory, so it might create a performance issue.

But there are certain situation where Session could be lost:

  • 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 a web page is accessed through the original browser window. Browsers differ on how they handle this situation.
  • If session time out occurs.
  • If you call the method Session.Abandon() programmatically in any web page of the site.
  • If restart IIS.

Below is an example that stores a dataset in the session:

Session["Employees"]=dsEmployee;

How to optimize session state in asp.net?

Now, we will see how to optimize session state in asp.net. As sessions are stored in the sever so it is very much important to optimize session, so that performance will be better.

If no session is required for the application then make the session state mode as off in the web.config file like below:

<SessionState Mode="off"/>

When session state mode is off, Session will not be created for the client request. This will improve the performance of the web server.

Suppose in a page you need only to read session then try to implement page level session like below:

<% @ Page ……. EnableSession="ReadOnly" %>

In a page if you do not need session then disable the session like below:

<% @ Page ……. EnableSession="False" %>

If you need read and write to session then enable the session for the page.

<% @ Page ……. EnableSession="True" %>

This way you can make some optimization of the session.

How to increase session timeout period in asp.net?

Now we will see, how to increase the session timeout period in asp.net?

By default session timeout is 20 minutes but sometimes it is required to increase or decrease the session timeout as per application requirement. It is possible by a simple setting in the web.config file.

let’s say we have to increase session timeout to 60 minutes then make changes in the web.config files as:

We need to add some lines of code in the web.config file. There are different ways to set this.

Way-1

<system.web>
<sessionState timeout="60"></sessionState>
</system.web>

Way-2

<system.web>
<sessionState mode="InProc" cookieless="false" timeout="60" />
</system.web>

Way-3

<system.web>
<sessionState
mode="InProc"
stateConnectionString="tcpip=128.0.0.1:42424"
stateNetworkTimeout="60"
sqlConnectionString="data source=128.0.0.1;Integrated Security=SSPI"
cookieless="false"
timeout="60"/>
</system.web>

This is how we can increase session timeout period in asp.net.

Cookieless session in Asp.Net

Now we will discuss what is a cookieless session in Asp.Net.

When the browser is disabled with cookies then the session for the client will not be maintained. Because session id will be sent to the client browser in the form of an in-memory cookie.

  • The problem has been overcome in Asp.Net by supporting cookieless session.
  • When the session id is appended to the URL in the form of Query string then it is called cookieless session.
  • To use cookieless session we have to modify in the web.config file like below:
<SessionState ——- Cookieless="ture/false" timeout="20" />

The URL looks like below:

http://—–\(12AB———-)

last is the session id which is appended as query string parameter.

When the client makes changes with the URL the session will be lost. This makes a new session to be created for the client.

How to know if browser supports cookie or not:

Request.Browser.Cookies

If it returns true means browser supports cookie and if it returns false then the browser does not support cookie.

Asp.Net state management interview questions

Here, we will discuss a few asp.net statemanagement interview questions.

  • What are the different state management techniques available in asp.net?
  • What are the client-side state management techniques?
  • What are the server-side statemanagement techniques?
  • What is the difference between client-side state management technique and server-side state management technique?
  • Where the view state data will be stored?
  • Is it possible to store view state in the server-side?
  • How do you enable or disable a ViewState for control on the page?
  • How do you enable or disable a ViewState at the page level?
  • Difference between Session and Cache?
  • What is ViewState? What are the advantages and disadvantages of view state?
  • What are cookies? How many types of cookies are there?
  • What are the advantages and disadvantages of cookies in Asp.Net?
  • What is the difference between Session Cookies and Persistent Cookies?
  • How do you create a Cookie that never expires?
  • What are the limitations of the query string?
  • What is a Session?
  • What is the default session timeout period? And how we can change the session timeout?
  • How do you end a user session?
  • How to store sessions in SQL server database?
  • What are the in-proc and out-proc sessions in asp.net?
  • What is the difference between sessions and applications?
  • What are the cookieless session in asp.net?
  • What are the Session State Modes?

You may like following asp.net tutorials:

This asp.net tutorial, we discussed various state management techniques in asp.net. And also, we learned about below things:

  • View state in Asp.Net
  • Query String in Asp.Net
  • Cookies in asp.net
  • Session management in Asp.Net
  • How to optimize session state in asp.net?
  • How to increase session timeout period in asp.net?
Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

>