Request / Response Objects

Intertech Tutorials

Request / Response Objects

Because of ASP.NET’s improved object model, much of the functionality of the Request and Response objects has been deprecated. There remain other uses for these objects. You can work with cookies, redirect users, check browser capabilities and even send binary information down the output stream.

Every time a user clicks on a link, button or other type of control on a Web page, it forms and sends a request to the Web server, ultimately to be processed by ASP.NET. In ASP.NET, The Request object is a type of System.Web. HttpRequest. As a developer, you can “interrogate” the incoming request in your code-behind file.

Here are the core properties of interest:

Members of System.Web.HttpRequest Meaning in Life
ApplicationPath Gets the virtual path to the currently executing server application.
Browser Provides information about the client's Web browser capabilities.
Cookies Indicates the virtual path of the current request. This property is read-only.
FilePath Indicates the virtual path of the current request. This property is read-only.
Files Gets the collection of client-uploaded files (Multipart MIME format).
Form Gets a collection of Form variables.
Headers Gets a collection of HTTP headers.
HttpMethod Indicates the HTTP data transfer method used by client (GET, POST). This property is read-only.
IsSecureConnection Indicates whether the HTTP connection is secure (that is, HTTPS). This property is read-only.
Params Gets a combined collection of QueryString + Form+ ServerVariable + Cookies.
QueryString Gets the collection of QueryString variables.
RequestType Indicates the HTTP data transfer method used by client (GET, POST)
ServerVariables Gets a collection of Web server variables.
UserHostAddress Gets the IP host address of remote client.
UserHostName Gets the DNS name of remote client.
SaveAs() Allows you to save the entire request a text file.

In classic ASP, you may have used the Request object to interact with control data by working with the Request. QueryString or Request.Form collections. The ASP.NET HttpRequest object still supports these collections; however they are considered obsolete.


// This is the old ASP way! Don’t do this!
string userName = Request.Form["txtUserFirstName"];
Response.Write(userName);

The ASP.NET Page programming model automatically maps the HTML form values to the server controls. Each Web server control has an ID attribute, enabling each control a unique identity. Therefore, you are able to get and set values of objects in an identical manner as a Windows Forms application. The controls will use this information to render back their markup.


// This is the ASP.NET way! Do this!!
string userName = txtUserFirstName.Text;
myLabel.Text = userName;

The Browser property of the Request class provides access to an internal HttpBrowserCapabilities object. Using this type, you are able to discover the Web browser type being used and the capabilities it supports.

Consider the following VB code which builds a string containing various bits of Web browser information and assigns it to a Label control.


Public Sub ShowBrowserInfo()
' Get information regarding the requesting client.
Dim theInfo As String = "Browser capabilities:<br>"
theInfo += String.Format("Is the client AOL? {0}<br>", Request.Browser.AOL)

theInfo += String.Format("Does the client support ActiveX? {0}<br>", _
    Request.Browser.ActiveXControls)
theInfo += String.Format("Does the client support Applets? {0}<br>", _
    Request.Browser.JavaApplets)
theInfo += String.Format("Does the client support Cookies? {0}<br>", _
    Request.Browser.Cookies)
theInfo += String.Format("Does the client support VBScript? {0}<br>", _
    Request.Browser.VBScript)

' Now assign it to a Label on the page.
lblOutput.Text = theInfo
End Sub

asp15

asp24-511x210

The Response property of the Page class provides access to an internal HttpResponse type. This type defines a number of properties that allow you to format the HTTP response that is being sent back to the client Web browser. The HttpResponse type defines numerous properties and collections - most notably the Cache and Cookies collection, which is covered in the State chapter. The HttpResponse type also provides a number of important members:

Members of System.Web.HttpResponse Meaning in Life
ContentType Gets or sets the HTTP MIME type of the output stream.
Cookies Gets the Response’s cookie collection.
Output Enables text output to the Web browser.
OutputStream Enables binary output to the Web browser.
Request Gives access to the related Request object.
Clear() Clears all headers and content output from the buffer stream.
Close() Closes the socket connection to a client.
End() Sends all currently buffered output to the client then closes the socket connection.
Flush() Sends all currently buffered output to the client.
Redirect() Redirects a client’s Web browser to a new URL.
SetCookie() Sets a cookie to a particular value.
Write() Writes values to an HTTP output content stream. This is provided for backwards compatibility with classic ASP and should not be called.
WriteFile() Writes the contents of a file on the Web server directly to an HTTP output stream.

If you have a background in classic ASP, you know that Response.Write() was the preferred manner to inject HTML markup into the outgoing response. Under ASP.NET this approach is considered obsolete and deprecated! You now alter the HTML response by referencing a Web control by its ID and set its properties.

As a matter of fact, if you insist on using Response.Write() with ASP.NET, you’ll find that it is rendered entirely after of the Controls are rendered. Study the following code examples. Here we have a simple .aspx page with a button on it.

asp18-524x314

The code-behind file looks like this:


Partial Class Default3
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Response.Write("Hello, World!") ' BAD!!!
End Sub
End Class

What’s the output? This…

asp19

Nothing wrong with that, right? Well, take a look at the Web browser’s HTML source code. Whoops!

asp20-544x293

Instead, a label should have been used. The click event handler will set the Text property of the label, and it would be inserted into the proper location with the HTML markup.

This is how it will look when completed. You can see that a label control was added.

asp20-535x288

The code is changed to set the Text property of the label control.


Partial Class Default3
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Label1.Text = "Hello, World!" ' GOOD!!!
End Sub
End Class

Note that “Hello World” now appears below the button.

asp21

When you view the HTML source code that was sent back to the Web browser, the label kept its ID, “Label1”, and was transformed into a <span> element.


<head><title>
  Untitled Page
</title></head>
<body>
<form name="form1" method="post" action="Default3.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="
/wEPDwUKLTMyNDcxODYzNQ9kFgICAw9kFgICAw8PFgIeBFRleHQFDUhlbGxvLCBXb3JsZCFkZGQPHjDXeaKaubt7FxZNFpgZ2WBCVw==" />
</div>
<div>
<input type="submit" name="Button1" value="Button" id="Button1" />
</div>
<span id="Label1">Hello, World!</span>
<div>
  <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"
value="/wEWAgK1wu+QCwKM54rGBqDQVLzqq6A8iPzHX8xmUWDHjlPd" />
</div></form>
</body>
</html>

Page Events

ASP.NET is an event-based system, just like a traditional desktop application. This becomes extremely clear when you examine the role of Web Controls later in the course.

An ASP.NET Page derived type also has a very clear lifecycle and can handle various events defined in the Page class or inherited from the Control class.

asp26-474x494

Here is a breakdown of the events and how you can use them in event handlers:

Remember, some of these events are shared by each of the controls while others are just used by the Web page. The Page events are specific to the page processing lifecycle.

Creating Page event handlers in VB is easy. Just choose “(Page Events)” on the left side and choose the event that you want to handle on the right side:

asp27-526x313

Notice how it created the full event handler, with “sender as Object and e as EventArgs”.

C# developers cannot do this. They must type in these event handlers manually. Specifically, C# developers using the code-behind model must have all possible events memorized, including the method signatures of the event handlers. However, C# developers using the single-file model can create the event handlers automatically.

One way C# developers can create event handlers automatically is to use custom snippets to insert event handlers.

asp28-528x228

You will install these snippets and use them in your lab.

As you can see here, C# developers do have access to the page events if they are using the single-file model.

asp29-497x300

The IsPostBack Property

As you work on ASPX, ASCX and MASTER files, you’ll consistently be working within the Page_Load event handler. Here, you’ll be dynamically setting the state of your controls with data from Web Services, a database, files, etc.

The Load event is fired each and every time the page is loaded via an incoming HTTP Request. Therefore, if you were to populate a list box control within the Load event handler (below), it is reloaded each and every time (even during post-back)!


// C#
private void Page_Load(object sender, System.EventArgs e)
{
// The list box is loaded every time!
myListBox.Items.Add("First");
myListBox.Items.Add("Second");
myListBox.Items.Add("Third");
myListBox.Items.Add("Fourth");
}



' VB
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Me.Load
' The list box is loaded every time!
myListBox.Items.Add("First")
myListBox.Items.Add("Second")
myListBox.Items.Add("Third")
myListBox.Items.Add("Fourth")
End Sub

After clicking the button several times, check out the awesome results!

asp30-316x382

Whoops! Every time you click the button, it forces a post back to the Web server, which adds the same four strings to the control! Not cool. Just to be clear, there is no Button.Click event handler written for the button.

To ensure that a block of code within the Page_Load event handler is only executed during the initial loading of a page, you will use the Boolean IsPostBack property. The list box’s contents will not be re-added if the page is posting back to itself. The contents of the control are automatically stored in a hidden form field called __VIEWSTATE, which you will learn about in the State chapter.


// C#
private void Page_Load(object sender, System.EventArgs e)
{
if (!IsPostBack)
{
// The list box is loaded once!
myListBox.Items.Add("First");
myListBox.Items.Add("Second");
myListBox.Items.Add("Third");
myListBox.Items.Add("Fourth");
}
}



' VB
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
' The list box is loaded once!
myListBox.Items.Add("First")
myListBox.Items.Add("Second")
myListBox.Items.Add("Third")
myListBox.Items.Add("Fourth")
End If
End Sub

A good way to test Web pages, user controls and master pages is to set a break point on each of the Page_Load event handlers in these files. This allows you to step through the code as the state information is retrieved and bound to the controls. This is especially useful when pages are nested in Master pages or user controls are nested in Web pages (or even parent user controls!).


Copyright (c) 2008-2013. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.