ASP.NET Intrinsic Objects

Many features of ASP.NET are similar to the previous versions of ASP. Familiar intrinsic objects such as Request, Response, Server, Application, and Session are part of ASP.NET and are used in much the same way as they were in ASP. However, in ASP.NET these objects are defined in new classes in the System.Web namespace.

Some ASP.NET objects function exactly as they did in ASP. Response.Write("some output") is an example of an object that performs exactly the same as in previous versions of ASP. The values returned by some ASP.NET methods are different from those in ASP and in some cases must be coded differently.

Namespaces

The objects of ASP.NET are divided according to object classes. There are many object classes, and they are grouped in namespaces. Thus a namespace has many object classes. At the top of the object class hierarchy is the System Namespace.

The System.Web Namespace

The System.Web namespace supplies classes and interfaces that enable browser-server communication. This namespace includes the HttpRequest class which provides extensive information about the current HTTP request, the HttpResponse class which manages HTTP output to the client, and the HttpServerUtility class which provides access to server-side utilities and processes. System.Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control.

The Page Class

The Page class represents an .aspx file, also known as a Web Forms page, requested from a server that hosts an ASP.NET Web application. The page class is part of the system.Web.UI namespace. The page class provides access to a range of other objects created from classes in the System.Web namespace. Using the properties and methods of these objects, we can perform activities such as:

  • Redirect a user to another page
  • Find out about the web browser the user is using
  • Find out what web site the user was before coming to our site
  • Personalize pages for our visitors

ASP.NET Core Objects

There are several built-in objects. They are:

Request – Gives access to information about the person or process requesting the web page

Response – Provides a way for us to accurately control how the response is sent back to the person who made the request

Server – Provides a range of useful web-related utilities

Application – Implements a useful site-wide storage location for frequently used information

Session – Makes it possible for us to store information for each user’s session, for example, a shopping cart.

Each of these objects is created from a class. For example, the response object from the System.Web.HttpResponse class. However, this object is accessible from a property of the Page object, called response. Similarly, the application, request, server, and session objects are accessible from the corresponding page properties.

The Request Object

The Request object enables ASP.NET to read the HTTP values sent by a client during a Web request. Following are some of the commonly used properties and methods of the Request object.

Properties

ApplicationPath / Gets the ASP.NET application's virtual application root path on the server.
Browser / Gets information about the requesting client's browser capabilities.
ClientCertificate / Gets the current request's client security certificate.
ContentType / Gets or sets the MIME content type of the incoming request.
Cookies / Gets a collection of cookies sent by the client.
FilePath / Gets the virtual path of the current request.
IsSecureConnection / Gets a value indicting whether the HTTP connection uses secure sockets (that is, HTTPS).
PathInfo / Gets additional path information for a resource with a URL extension.
PhysicalPath / Gets the physical file system path corresponding to the requested URL.
QueryString / Gets the collection of HTTP query string variables.
ServerVariables / Gets a collection of Web server variables.
UserHostAddress / Gets the IP host address of the remote client.
Methods
GetType (inherited from Object) / Gets the Type of the current instance.
MapImageCoordinates / Maps an incoming image-field form parameter to appropriate x/y coordinate values.
MapPath / Overloaded. Maps the virtual path in the requested URL to a physical path on the server for the current request.
SaveAs / Saves an HTTP request to disk.
ToString (inherited from Object) / Returns a String that represents the current Object.
ValidateInput / Validates data submitted by a client browser and raises an exception if potentially dangerous data is present.

The following example demonstrates how to check the browser version using the Request object.

Run BrowserCheck.aspx

Response Object

The Response object provides access to the HTTP reply that is going to be sent from the web server to the browser. Following are some of the common properties and methods of the Response object.

Properties
Buffer / Gets or sets a value indicating whether to buffer output and send it after the entire response is finished processing.
Charset / Gets or sets the HTTP character set of the output stream.
Cookies / Gets the response cookie collection.
Expires / Gets or sets the number of minutes before a page cached on a browser expires. If the user returns to the same page before it expires, the cached version is displayed. Expires is provided for compatiblility with previous versions of ASP.
Output / Enables output of text to the outgoing HTTP response stream.
Status / Sets the Status line that is returned to the client.
SuppressContent / Gets or sets a value indicating whether to send HTTP content to the client.
Methods
BinaryWrite / Writes a string of binary characters to the HTTP output stream.
Clear / Clears all content output from the buffer stream.
Flush / Sends all currently buffered output to the client.
Pics / Appends a PICS-Label HTTP header to the output stream.
Redirect / Overloaded. Redirects a client to a new URL.
ToString (inherited from Object) / Returns a String that represents the current Object.
Write / Overloaded. Writes information to an HTTP output content stream.
WriteFile / Overloaded. Writes the specified file directly to an HTTP content output stream.

Examples:

The following example shows how the Write method of the Response object is used in the ASP.NET page. Note also the use of inline scripts.

Run Buffer.aspx

The following is a similar program written in block script using the Page_Load subroutine.

Run Buffer1.aspx

Let us look into another example where WriteFile method is used to display the contents of a text file saved in the same folder as the program.

WriteFile.aspx

MyFile.txt

Run WriteFile.aspx

Server Object

The Server object provides some utilities that help processing Web requests such as mapping physical path of a logical web server file path. Some of the common properties and methods of the Server object are following.

MachineName / Gets the server's computer name.
ScriptTimeout / Gets and sets the request time-out in seconds.

Properties

Methods
Execute / Executes the current request using another page.
HtmlEncode / Encodes a string to be displayed in a browser.
MapPath / Returns the physical file path that corresponds to the specified virtual path on the Web server.
ToString (inherited from Object) / Returns a String that represents the current Object.
Transfer / Terminates execution of the current page and begins execution of a new page for the current request.

Example:

The following example illustrated how the mappath method is used to get the full-path of a file from a virtual folder.

Run mappath.aspx

ASP.NETState Management

HTTP is a stateless protocol, which means that it does not automatically indicate whether a sequence of requests is all from the same client or even whether a single browser instance is still actively viewing a page or site.

As a result, building Web applications that need to maintain some cross-request state information (shopping carts, data scrolling, and so on) can be extremely challenging without additional infrastructure help.

ASP.NET provides two objects, application and session, to manage states of an application.

Application Object

An ASP.NET application is the sum of all files, pages, handlers, modules, and code that reside in a given virtual directory and its subdirectories and that users can request through that virtual directory hierarchy.

Application state includes any piece of information or data that affects the behavior of the application: catalogs, shopping carts, user options, lists of reviews, and hit counters are all examples.

The most common way to access application state is by means of the Application property of the Page object. Application-state variables are, in effect, global variables for a given ASP.NET application.

These variables are usually set in the Application_OnStart event in the global.asax file and then accessed and modified in individual ASP.NET pages. The global.asax file is placed in the root folder of the Web site.
In the following example, the company telephone and address are assigned in the global.asax file as shown. The file is placed in the root folder of the Web site.

Global.asax

The following ASP.NET file (application2.aspx) is used read the values of the variables set in the global.asax file.

Application2.aspx

Run application2.aspx

Session Object

ASP.NET provides the cross-request state information (shopping carts, data scrolling, and so on) infrastructure that Web applications require, with built-in session-state functionality that enables you to take the following actions:

Automatically identify and classify requests coming from a single browser client into a logical application session on the server.

Store session-scoped data on the server for use across multiple browser requests.

Raise appropriate session-lifetime management events (Session_OnStart, Session_OnEnd, and so on) that can be handled in application code.

Automatically release session data if the browser does not revisit an application within a specified time-out period.

The following code mimics some of the characteristics of a shopping basket. The page will have the capability adding and deleting an item from a shopping cart.

Run session.aspx

Identifying a Session

Each active ASP.NET session is identified and tracked using a SessionID string containing only the ASCII characters that are allowed in URLs. SessionID values are generated using an algorithm that guarantees uniqueness so that sessions do not collide, and randomness so that a malicious user cannot use a new SessionID to calculate the SessionID of an existing session.

The SessionID strings are communicated across client-server requests either by means of an HTTP cookie or a modified URL with the SessionID string embedded, depending on how you configure the application settings.

The following code displays session id’s of the users coming to our Web site. Try connecting to our site from various client machines.

Customers.aspx

Global.asax

Run customers.aspx

Cookies

Cookies are used to maintain information about an individual user across sessions. Because clients can delete their cookies at any time, your Web application should not be dependent upon the existence of a cookie.

The cookie file stores the name of the cookie, the value, and the name of the server that wrote the cookie.

Storing the cookies on the client computers provides a means of automating activities such as the login process or filing out a form.

Writing a Cookie:

ASP provides a simple method to write and read cookies. Cookies are written using the response object, and read using the request object. The Response object supports a collection named Cookies, to which cookies are added.

To create a cookie you name the cookie and give it a value. You must also identify when the cookie expires.

Cookies can be added to the Response.Cookies collection in a couple of ways. The following are two examples of writing a simple cookie using an absolute expiration date.

Response.Cookies("userName").Value = "mike"

Response.Cookies("userName").Expires = DateTime.Now.AddDays(1)

Dim aCookie As New HttpCookie("lastVisit")

aCookie.Value = DateTime.Now.ToString

aCookie.Expires = DateTime.Now.AddDays(1)

Response.Cookies.Add(aCookie)

It is easy to look at the cookies — they are text files. The cookie files are user-specific, so they are isolated by account. In Windows XP, for example, you will find the cookie files in a directory with a name such as the following:

c:\Documents and Settings\<user>\Cookies

You can open the cookie with a text editor. If the file contains multiple cookies, they are separated with an asterisk (*). The first line of each cookie is its name, and the second has the values. The remaining lines have cookie housekeeping information such as the expiration date and time.

There is also a simple checksum in the cookie; if you change the length of the cookie name or value, the browser will detect the tampering and will discard the cookie.

Example:

In the following example a cookie is written with cookiename “username” that has a value “Mike”.

Run Cookie.aspx

Reading a Cookie:

You can retrieve a cookie’s value using the request object.

<% Request.Cookies(“CookieName”).value %>

Example-2: The following code writes a cookie in the client computer with the cookie name = background and with a value selected by the drop-down list.

Run Cookie1.aspx

The following code (cookie2.aspx) is used to read the value of the cookie set by the cookie1.aspx file (above) and the background color of the page is set by the cookie value read.

Run Cookie2.aspx

1