Request/Response Objects
Most of the information needed to produce Web pages comes from external files and
databases, with additional content hard coded on the page. There are, in addition, built-in
sources of data that you might find useful. The Visual Basic language includes numerous
data and time functions, for example, that can be accessed and added to a page. The ASP.NET
environment, as well, supplies data sources that can be valuable in personalizing content
for visitors arriving at your site.
For example, URL requests for Web pages are accompanied by information pertaining
to the request itself. This information identifies the source of the request as well
as the server path to the page being retrieved. Under ASP.NET, the HttpRequest class provides
a Request object that contains this information as a set of
properties. These properties can be investigated to determine, for instance, the type of browser
the visitor is using and the IP (Internet Protocol) address of the URL request, among other
items of useful information.
Parallel to the Request object is the
Response object provided through the HttpResponse class. This object
deals with writing output to a Web page, and contains a couple of useful methods for writing
page content and redirecting navigation to different pages. The Request
and Response objects can be used as sources of information content
and control to produce Web pages responsive to characteristics of a user's visit.
Request Object Properties
The following output displays several properties of the Request object,
detailing browser and operating system characteristics pertaining to your current visit to this
page.
Properties of your request for this page:
Browser Type: Unknown
Browser Version: 0.0
Browser Platform: Unknown
Figure 3-49. Using the Request object to determine browser properties.
<%@ Page Language="vb" Debug="True" %>
<SCRIPT Runat="Server">
Sub Page_Load
Browser.Text = Request.Browser.Browser
BrowserVersion.Text = Request.Browser.Version
BrowserPlatform.Text = Request.Browser.Platform
End Sub
</SCRIPT>
<form Runat="Server">
<h4>Properties of your request for this page:</h4>
<b>Browser Type: </b><asp:Label id="Browser" Runat="Server"/><br/>
<b>Browser Version: </b><asp:Label id="BrowserVersion" Runat="Server"/><br/>
<b>Browser Platform: </b><asp:Label id="BrowserPlatform" Runat="Server"/>
</form>
Listing 3-54. Code to display Request object properties.
The values shown are produced by the server when this page is loaded. These values
represent the browser you are currently using to view this page. Because there are differences in
browsers (different brands and different versions), Web pages sometimes need to be coded differently
to compensate for limitations in some browsers and to take advantage of advanced features in others.
If a script can determine the type of browser being used, then it can generate appropriate code for
that particular browser.
The following table lists several properties of the Request object,
and displays values associated with your current real-time URL request for this page.
| Browser Properties |
Values Associated with Your Current Visit |
| Request.UserAgent |
The full identification of the browser requesting the page:
CCBot/1.0 (+http://www.commoncrawl.org/bot.html) |
| Request.Browser.Browser |
The type of browser making the request:
Unknown |
| Request.Browser.Type |
The type and major version of the browser making the request:
Unknown |
| Request.Browser.Version |
The major and minor versions of the browser request:
0.0 |
| Request.Browser.MajorVersion |
The major version of the browser making the request:
0 |
| Request.Browser.MinorVersion |
The minor version of the browser making the request:
0 |
| Request.Browser.AOL |
Whether this is an AOL browser:
False |
| Request.Browser.Frames |
Whether the browser supports frames:
False |
| Request.Browser.JavaScript |
Whether the browser supports JavaScript:
False |
| Request.Browser.Platform |
The type of operating system under which the browser is running:
Unknown |
| Request.IsSecureConnection |
Whether the current connection uses a secure Web protocol:
False |
| Request.UserHostAddress |
The IP address from which the browser is requesting the page:
38.107.179.227 |
| Server Properties |
|
Request.ServerVariables ("LOCAL_ADDR") |
The IP address of the server hosting the requested page.
74.208.73.193 |
| Request.Url.Host |
The URL of the server hosting the requested page:
www.maconstateit.net |
| Request.RawUrl |
The portion of the URL request following the domain information:
/tutorials/aspnet20/ASPNET03/aspnet03-07.aspx |
| Request.Url.Scheme |
The type of URL request:
http |
| Request.Url.Port |
The port through which the URL request is made:
80 |
| Request.ApplicationPath |
The virtual path to the root directory containing the page requested by the browser:
/tutorials |
| Request.FilePath |
The virtual path to the page requested by the browser:
/Tutorials/ASPNET/ASPNET03/aspnet.aspx |
| Request.PhysicalApplicationPath |
The physical path to the root directory of the page requested by the browser:
c:\Tutorials\ |
| Request.PhysicalPath |
The physical path to the page requested by the browser:
c:\Tutorials\ASPNET\ASPNET03\aspnet.aspx |
Figure 3-50. Properties of the Request object.
Using Inline Expressions
The above property values are displayed on this page by including in-line expressions within the
XHTML code. For example, in the above table the type and major version of the browser you are
using to view this page are displayed inside a table cell with the following code.
...
<tr>
<td>Request.Browser.Type</td>
<td>The type and major version of the browser making the request:<br/>
<b><%= Request.Browser.Type %></b>
</td>
</tr>
...
Listing 3-55. Code to display Request property as in-line expression.
An in-line expression is used to embed information taken from the HTTP header
representing your URL request. After this information is plugged into the page, it is returned
to your browser for viewing.
Using an in-line expression is an alternative to using an <asp:Label>
control as the target for script output. In the case of in-line expressions, there is no
need for a separate script block or subprogram to produce the output. The script itself is
contained inside the in-line expression, here to display the Browser.Type
property of the Request object making the request for this page.
Whether you use Label controls or in-line expressions to display server values is often a matter
of programmer preference. For instance, an <asp:Label> control could
have been used for the above browser-type display, along with a script to populate the control.
Sub Page_Load
BrowserType.Text = Request.Browser.Type
End Sub
...
<tr>
<td>Request.Browser.Type</td>
<td>The type and major version of the browser making the request:<br/>
<b><asp:Label id="BrowserType" Runat="Server"/></b>
</td>
</tr>
...
Listing 3-56. Code to display Request property through Label control.
In order to display all Request properties shown in the above table,
an <asp:Label> control would be needed for each property, along
with a value assignment statement for each control. This extra coding is avoided by using in-line
expressions as convenient value-display techniques.
Separating Design from Scripting
If you are following strict ASP.NET coding practices, you will tend to avoid using in-line
expressions. Although this was common practice under classical ASPsimply because there were
no alternativesit is discouraged under ASP.NET. The reasoning is that there should be no
intermixing of XHTML code and script. The XHTML section of the page should contain only XHTML
code, literal text content, and server controls. All scripts should appear only in the
script block at the top of the page. This argues, then, for using <asp:Label>
controls as script targets to produce the above table.
The rationale behind this argument has to do with separating Web page design from Web page
scripting. In certain development shops these are two separate work processes. That is, a team of
page designers and graphic artists are busy designing the look and feel of a Web site, while a
different team of programmers is cranking out the code. By keeping page design separate from page
scripting, it is not necessary that either team take part in, or perhaps even be aware of, the other's
activities.
Perhaps in some development shops this is common practice. Still, it is doubtful that full
separation is possible. Somebody will need to peek over somebody else's shoulder sometime during
the process. In smaller Web development shops, a single person or a small development group
often has responsibility for both aspects of page development. In these circumstances, it is
impractical to completely separate the two, especially with the designer-and-programmer roles
occupied by most Web professionals.
Thus, a compromise is in order to the strict enforcement of design and programming separation.
A good heuristic is to keep design and coding separate where practical. There usually are design
clarity and coding convenience in keeping all script together in one place and separate from
the XHTML portion of the page. However, it's nothing to fall on your sword over, and in some cases
virtually impossible to achieve.
Response Object Methods
The Response object provides control over the format and content
of output sent to a Web page. Like the Request object, it has
built-in properties and methods that are activated through scripts. Many of the features of the
Response object pertain to special programming needs and are not
appropriate or necessary for common use. Two useful methods are shown in the following table.
| Response Method |
Description |
| Response.Redirect("url") |
Immediately redirects to and loads a different Web page.
|
| Response.Write(content) |
Writes text or variables to a Web page:
Response.Write("Text string"): Text string |
Figure 3-51. Methods of the Response object.
Probably the most useful of the methods is Response.Write(),
especially when it comes to debugging scripts. You can write the contents of variables or display
"trace flags" to track progress through a script. In the following example,
Response.Write() statements are placed throughout a script to trace its processing sequence
and to write the contents of a variable. They are not part of normal processing of the script;
they simply provide visual indication of reaching certain checkpoints during processing.
<SCRIPT Runat="Server">
Sub ProcessThis (Src As Object, Args As EventArgs)
Response.Write("Start of ProcessThis" & "<br/>")
Response.Write("End of ProcessThis" & "<br/>")
ProcessThat
End Sub
Sub ProcessThat
Response.Write("Start of ProcessThat" & "<br/>")
Dim VarA = "Howdy"
Response.Write("Value of VarA = " & VarA & "<br/>")
Response.Write("End of ProcessThat" & "<br/>")
End Sub
</SCRIPT>
<form Runat="Server">
<h4>Script Trace Button</h4>
<asp:Button Text="Trace" OnClick="ProcessThis" Runat="Server"/>
</form>
Listing 3-57. Code to display script trace points.
Click the following button to view the results of tracing this script. The button calls the
ProcessThis subprogram which, in turn, calls the
ProcessThat subprogram. Response.Write()
statements embedded in the code display script progress. After clicking the button, scroll to
the top of this page to view the output. If the sequence of outputs does not follow your
assumed program logic, then you know something is wrong with your script.
Script Trace Button
Figure 3-52. Button to trace script execution.
Notice that since script blocks appear at the top of the page and are run prior to sending the
page to the browser, output from Response.Write() statements
also appears at the top of the page. This output location is not normally an issue since the
statements are being used only to trace script progress, not to produce final page output.
However, you can control where the output appears by including Response.Write()
statements within in-line scripts scattered throughout the page. For instance, the
following output is displayed in-place, where it is coded, by enclosing statements inside
the following in-line script.
<%
Response.Write("<b>Write this text string right here.</b><br/>")
Response.Write("<b>Write this text string on the next line.</b>")
%>
Listing 3-58. An in-line script to write to a Web page.
Write this text string right here.
Write this text string on the next line.
Figure 3-53. Output of in-line Response.Write() statements.
Using In-line Scripts
An in-line script is similar in structure to an in-line expression used previously to display
Request object output. Whereas an in-line expressionenclosed inside
<%= ... %> symbolsdisplays a single script value, an
in-line scriptenclosed inside <% ... %> symbolscontains
script code. The former is used to display a single property value or the value of a script
variable embedded on the page; the latter encloses one or more script statements to carry out
server processing. It is a way of embedding script inside the HTML section of a page.
One of the uses of in-line scripts is to control XHTML output appearing on the page. Imagine,
for instance, that a paragraph of coded text is displayed only under certain visitor circumstances.
An in-line script can determine whether or not to display this text.
<% If Request.Browser.Browser <> "IE" Then %>
<h3>Warning!</h3>
<p>You are not using Internet Explorer to view this Web page. There are
features you will not be able to view. Please do yourself and all Web
developers a favor by downloading and using this browser. You are not
welcome to my page unless you do so immediately.</p>
<% Else %>
<h3>Congratulations!</h3>
<p>You are using Internet Explorer to view this Web page. There are
features you will be able to view that are not possible under different
browsers. Therefore, enjoy full, modern Web page output below.</p>
<% End If %>
... rest of Web page
Listing 3-59. Embedding in-line scripts on a Web page.
Notice that the script statements to check for browser type are embedded within the XHTML
portion of the page. In this case, the lines of code enclosing blocks of XHTML present a
condition test under which one of the XHTML blocks is displayed. The following output of this
code pertains to your visit to this page.
Warning!
You are not using Internet Explorer to view this Web page. There are features you will
not be able to view. Please do yourself and all Web developers a favor by downloading and
using this browser. You are not welcome to my page unless you do so immediately.
...
rest of Web page
Figure 3-54. Page output using in-line scripts.
As in the case of in-line expressions, there are alternatives to in-line scripts such that
script code can remain separate from XHTML code. One alternate is to replace the hard-coded
text with an <asp:Label> control. The condition test and the
output text shown above can then be moved to the script section of the page.
<SCRIPT Runat="Server">
Sub Page_Load
If Request.Browser.Browser <> "IE" Then
Message.Text = "<h3>Warning!</h3>" & _
"<p>You are not using Internet Explorer to view this Web page. " & _
"There are features you will not be able to view. Please do " & _
"yourself and all Web developers a favor by downloading and " & _
"using this browser. You are not welcome to my page unless you " & _
"do so immediately.</p>"
Else
Message.Text = "<h3>Congratulations!</h3>" & _
"<p>You are using Internet Explorer to view this Web page. There " & _
"are features you will be able to view that are not possible " & _
"under different browsers. Therefore, enjoy full, modern Web " & _
"page output below.</p>"
End If
End Sub
</SCRIPT>
<form Runat="Server">
<asp:Label id="Message" Runat="Server"/>
... rest of Web page
</form>
Listing 3-60. Using script blocks instead of in-line scripts.
There are other options to conditionally display page content, and these are discussed later.
The point is the same as that made about in-line expressions. Where possible, keep scripting out
of the XHTML portion of the page. Although doing so provides tempting convenience, it is a
practice best left undone, but again, not to fall on your sword for.
Page Redirection
Another handy Response method is
Response.Redirect(). This statement permits, under program control, issuance of a
URL to a different Web page. When the statement is executed, the current page is immediately
unloaded and the identified page is loaded. This page-transfer technique comes into play
when your site contains multiple pages and where processing flows from one page to the
next under script control.
You can see how this method works by clicking the following button. This button calls a
subprogram which redirects you to the opening page of this tutorial.
Redirection Button
Figure 3-55. Page navigation using Response.Redirect().
<SCRIPT Runat="Server">
Sub Go_Home (Src As Object, Args As EventArgs)
Response.Redirect("../Title.htm")
End Sub
</SCRIPT>
<form Runat="Server">
<h4>Redirection Button</h4>
<asp:Button Text="ASP.NET Home" OnClick="Go_Home" Runat="Server"/>
</form>
Listing 3-61. Scripting Web page redirection with Response.Redirect() method.
The redirected URL appears inside the parentheses of the Response.Redirect()
method. This parameter can be a quoted URL string (a relative or absolute URL address), or
it can be a variable containing a URL string.
It should be noted that the redirected page opens in the current browser window. There is no
way to target the page to a new window or to a different frame in a frameset. The reason is simply
that windows and frames are strictly browser phenomena. The server which executes this command has
no awareness of the desktop or browser layout that is the source of the redirection command.