Application and Session Objects in ASP.NET Wednesday, Oct 13 2010 

Application and Session Objects in ASP.NET

Sessions serve as a way to transport and maintain user data in web pages, such as forums, or e-commerce websites. In this article, We take a quick tour of both session and application objects, and gives us practical examples as to their uses.  



 

So what is a session?

session is the time for which a particular user interacts with a web application. During a session the unique identity of the user is maintained internally. A session ends if there is a session timeout or if you end the visitor session in code.

What’s the use of sessions?

Sessions helps to preserve data across successive accesses. These can be done on a per user basis, via the use of session objects. Session objects give us the power to preserve user preferences and other user information when browsing a web application. To better understand the use of sessions, consider an example: Suppose you own a website in which you give the visitors the option to choose the background color of the pages they will browse. In such a case you need to remember the user’s choice on each of the page. This task can be accomplished using sessions.

A more practical example is the case of an e-commerce website where the visitor browses through many pages and wants to keep track of the products ordered.

Application and Session Objects in ASP.NET – Our First Session

Sessions in ASP.NET are simply hash tables in the memory with a timeout specified. Consider the following examples

Session(“username”) = “Aayush Puri”

Session(“color”) = “Blue”

 

This assigns the values “Aayush Puri” and “Blue” to the session variables “username” and “color”, respectively. If I need to know the “username” or “color” in subsequent pages, I can use Session(“username”), Session(“color”).

Sessions in ASP.NET are identified using 32-bit long integers known as Session IDs. The ASP engine generates these session ID’s so that uniqueness is guaranteed.

Let’s now see how you can configure the session object depending on the requirements of your Web Application.

Session Type What it does Example
Session.Abandon Abandons (cancels) the current session.
Session.Remove Delete an item from the session-state collection. Session(“username”) = “Aayush Puri”
(
Initialize a session variable)
 

Session.Remove(“username”)
(
Deletes the session variable “username”)

Session.RemoveAll Deletes all session state items
Session.Timeout Set the timeout (in minutes) for a session Session.Timeout=30 (If a user does NOT request a page of the ASP.NET application within 30 minutes then the session expires.)
Session.SessionID Get the session ID (read only property of a session) for the current session.
Session.IsNewSession This is to check if the visitor’s session was created with the current request i.e. has the visitor just entered the site. The IsNewSession property is true within the first page of the ASP.NET application.

Application and Session Objects in ASP.NET – Application Objects

As we saw in the previous section, sessions help us preserve data on a per user basis. What if we want to initialize variables that are available in a session and that are the same for all users? This means that a change in the value of an application variable is reflected in the current sessions of all users. For example, we may like to fix variables like tax rate, discount rate, company name, etc., that will be specified once for all variables we can access in a session. This is whereapplication variables come in. Heck, they can even be used to show legal notices at the bottom of every page!

Creating an application variable is similar to session variables.

Application(“legal_notice”) = “No part of this article may be reproduced without prior permission”

 

There is a concern when changing the value of an application variable: at any particular instant, multiple sessions might be trying to change the value, although only one session can be allowed to change it. ASP.NET has an in built mutual exclusion for dealing with these types of problems.

  • Application.Lock – Locks the application variables
  • Application.Unlock – Unlocks the application variables

Once application variables are locked sessions that attempt to change them have to wait.

Application and Session Objects in ASP.NET – Practical Examples Showing the Use of Sessions

You might need to redirect the visitor to a particular page if some error has occurred. On the redirected page, you’ll need to display the error message. A session variable initialized to an error message fits the bill. Here’s an example: Suppose you are writing a function check_string() (as a part of page named page1.aspx) which accepts no other string than “ASP.NET Rocks!” If the string passed as an argument does not match, then you need to redirect to a page (“page2.aspx”) and display the error.
Page1.aspx:


Public Sub check_string(ByVal str As String)
If Not Str.equals("ASP.NET Rocks") Then
Session("error_message") = "The string was NOT ""ASP.NET Rocks"" "
Response.Redirect("page2.aspx")
End If
End Sub

 

Page2.aspx This next fucntion will display the error message.


Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Session("message") <> "" Then
Response.Write(Session("message"))
Session.Remove("message") 'Make the session variable null
End If
End Sub

 

I include this piece of code in the function “Page_load” to check for any error message on every visit to this page.

Here’s a personal example of having to use sessions: I had to design a website which had three types of users, all requiring authorization. All users were divided into three categories, and each category had a well defined set of rules and permissions.

While writing server-side scripts, I had to ensure that a particular script run only for qualified users. The information in thedatabase showed which user belonged to which category. Querying the database was too cumbersome, so a simple and elegant solution was to use session variables.

At the time of authorization I queried the category of the user and stored the result in a session variable.


At the time of authorization also fetch the category type
Session(“category”) = Get_category(username)

 

And that’s it–small, quick, and to the point. Would that all were as simple as sessions… but that’s neither here nor there. Enjoy!

Request Validation – Preventing Script Attacks Monday, Sep 20 2010 

Request Validation – Preventing Script Attacks

Once I stuck in same problem. I searched a lot then I got this solution.

This paper describes the request validation feature of ASP.NET where, by default, the application is prevented from processing unencoded HTML content submitted to the server. This request validation feature can be disabled when the application has been designed to safely process HTML data.

Applies to ASP.NET 1.1 and ASP.NET 2.0.

Request validation, a feature of ASP.NET since version 1.1, prevents the server from accepting content containing un-encoded HTML. This feature is designed to help prevent some script-injection attacks whereby client script code or HTML can be unknowingly submitted to a server, stored, and then presented to other users. We still strongly recommend that you validate all input data and HTML encode it when appropriate.

For example, you create a Web page that requests a user’s e-mail address and then stores that e-mail address in a database. If the user enters <SCRIPT>alert(“hello from script”)</SCRIPT> instead of a valid e-mail address, when that data is presented, this script can be executed if the content was not properly encoded. The request validation feature of ASP.NET prevents this from happening.

Why this feature is useful

Many sites are not aware that they are open to simple script injection attacks. Whether the purpose of these attacks is to deface the site by displaying HTML, or to potentially execute client script to redirect the user to a hacker’s site, script injection attacks are a problem that Web developers must contend with.

Script injection attacks are a concern of all web developers, whether they are using ASP.NET, ASP, or other web development technologies.

The ASP.NET request validation feature proactively prevents these attacks by not allowing unencoded HTML content to be processed by the server unless the developer decides to allow that content.

What to expect: Error Page

The screen shot below shows some sample ASP.NET code:

Running this code results in a simple page that allows you to enter some text in the textbox, click the button, and display the text in the label control:

However, were JavaScript, such as <script>alert("hello!")</script> to be entered and submitted we would get an exception:

The error message states that a �potentially dangerous Request.Form value was detected�� and provides more details in the description as to exactly what occurred and how to change the behavior. For example:

Request validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.

Disabling request validation on a page

To disable request validation on a page you must set the validateRequest attribute of the Page directive tofalse:

<%@ Page validateRequest="false" %>

Caution: When request validation is disabled, content can be submitted to a page; it is the responsibility of the page developer to ensure that content is properly encoded or processed.

Disabling request validation for your application

To disable request validation for your application, you must modify or create a Web.config file for your application and set the validateRequest attribute of the <pages /> section to false:

<configuration> <system.web> <pages validateRequest="false" /> </system.web> </configuration>

If you wish to disable request validation for all applications on your server, you can make this modification to your Machine.config file.

Caution: When request validation is disabled, content can be submitted to your application; it is the responsibility of the application developer to ensure that content is properly encoded or processed.

The code below is modified to turn off request validation:

Now if the following JavaScript was entered into the textbox <script>alert("hello!")</script> the result would be:

To prevent this from happening, with request validation turned off, we need to HTML encode the content.

How to HTML encode content

If you have disabled request validation, it is good practice to HTML-encode content that will be stored for future use. HTML encoding will automatically replace any ‘<’ or ‘>’ (together with several other symbols) with their corresponding HTML encoded representation. For example, ‘<’ is replaced by ‘&lt;’ and ‘>’ is replaced by ‘&gt;’. Browsers use these special codes to display the ‘<’ or ‘>’ in the browser.

Content can be easily HTML-encoded on the server using the Server.HtmlEncode(string) API. Content can also be easily HTML-decoded, that is, reverted back to standard HTML using the Server.HtmlDecode(string)method.

Resulting in: