ASP.NET Intrinsic Objects - University of Houston

advertisement
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.
Namespace
Web Class
Security Class
Data Class
Runtime Class
1
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
2
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.
Gets the physical file system path corresponding to
the requested URL.
Gets the collection of HTTP query string variables.
PhysicalPath
QueryString
ServerVariables
UserHostAddress
Gets a collection of Web server variables.
Gets the IP host address of the remote client.
3
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.
<%@ Page Language="VB" %>
<script language="vb" runat="server">
Sub Page_Load(Source As Object, E as EventArgs)
If Not IsPostBack Then
If Request.Browser.Browser = "IE" Then
If Request.Browser.MajorVersion < 6 Then
MyLabel.Text = "Time to upgrade Internet Explorer!"
Else
MyLabel.Text = "Your copy of Internet Explorer is up to date."
End If
Else
MyLabel.Text = "You're not using Internet Explorer"
End If
End If
End Sub
</script>
<html> <body>
<asp:Label id=MyLabel runat="server" Text=""/>
</body></html>
Run BrowserCheck.aspx
4
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.
Sets the Status line that is returned to the client.
Status
SuppressContent
Gets or sets a value indicating whether to send
HTTP content to the client.
Methods
Clear
Writes a string of binary characters to the HTTP
output stream.
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.
Overloaded. Redirects a client to a new URL.
BinaryWrite
Redirect
ToString (inherited from Object)
Write
WriteFile
Returns a String that represents the current
Object.
Overloaded. Writes information to an HTTP output
content stream.
Overloaded. Writes the specified file directly to an
HTTP content output stream.
Examples:
5
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.
<%@ Page Language="VB" %>
<html>
<body>
<%
Dim i As Integer
For i = 1 to 50
Response.Write(" X")
Next
%>
</body>
</html>
Run Buffer.aspx
The following is a similar program written in block script using the
Page_Load subroutine.
<script language="vb" runat="server">
Sub Page_Load
Dim Name as String
Name = "Mohamamd Rob"
Response.Write("My name is: ")
Response.Write(Name)
end sub
</script>
Run Buffer1.aspx
6
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
<%@ Page Language="VB" %>
<html>
<body>
<H2>Example of Reading and writing the contents of a file</br></H2>
<font color="red">
<%
Response.WriteFile("myfile.txt")
%>
</font>
</body>
</html>
MyFile.txt
This text is coming from a file located in the same folder as the program file.
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.
Properties
MachineName
Gets the server's computer name.
ScriptTimeout
Gets and sets the request time-out in seconds.
7
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.
<script language="VB" runat="server">
Sub Page_Load()
Dim filepath as String
response.write ("<b>The path of the file: </b>")
filepath= server.mappath("myfile.txt")
response.write (filepath)
end Sub
</script>
Run mappath.aspx
8
ASP.NET State 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 crossrequest 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
<script language="VB" runat="server">
Sub Application_OnStart()
Application("CompanyTelephone") = "(281) 283-5555"
Application("CompanyAddressLine1") = "2700 Bay Area Boulevard"
Application("CompanyAddressLine2") = "Houston, Texas 77058"
End Sub
</script>
9
The following ASP.NET file (application2.aspx) is used read the values of
the variables set in the global.asax file.
Application2.aspx
<%@ Page Language="VB" %>
<html>
<body>
<b>Company Address Line 1 = <% Response.Write(Application("CompanyAddressLine1")) %> </b> </br>
<b>Company Address Line 2 = <% Response.Write(Application("CompanyAddressLine2")) %> </b> </br>
<b>Company Telephone = <% Response.Write(Application("CompanyTelephone")) %> </b>
</body>
</html>
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 builtin 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.
10
<%@ Page language="VB"%>
<script language="vb" runat="server">
Sub EmptyClick(sender As System.Object, e As System.EventArgs)
Session("BasketCount") = 0
End Sub
Sub AddClick(sender As System.Object, e As System.EventArgs)
Session("BasketCount") += 1
End Sub
</script>
<html>
<body>
<form id="BasketForm" method="post" runat="server">
<asp:Button id="Empty" OnClick="EmptyClick" runat="server" Text="Empty"/>
<br />
<asp:Button id="Add" OnClick="AddClick" runat="server" Text="Add"/>
<br />
Basket items : <%=Session("BasketCount")%>
<br />
</form>
</body>
</html>
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.
11
Customers.aspx
<html>
<head><title>Customers on Site</title></head>
<body>
Customers:
<p><%=application("customers")%>
</body>
</html>
Global.asax
<script language="VB" runat="server">
sub session_onstart
application.lock
application("customers")=application("customers")&"Customer # " & session.sessionid
&_
" logged in at "& now()&"<br>"
application.unlock
end sub
</script>
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.
12
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.
13
Example:
In the following example a cookie is written with cookiename “username”
that has a value “Mike”.
<%@ Page Language="VB" %>
<script language="vb" runat="server">
Sub Page_Load(Source As Object, E as EventArgs)
Response.Cookies("username").value = "Mike"
Response.Cookies("userName").Expires = DateTime.Now.AddDays(1)
End Sub
</script>
<html>
<body>
<asp:label id=MyLabel runat="server" text="A cookie is added successfully to the
client machine"/>
</body>
</html>
Run Cookie.aspx
Reading a Cookie:
You can retrieve a cookie’s value using the request object.
<% Request.Cookies(“CookieName”).value %>
14
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.
<%@ Page Language="VB" %>
<script language="vb" runat="server">
Sub Page_Load(Source As Object, E as EventArgs)
If Not IsPostBack Then
MyButton.Text = "Save Cookie"
MyDropDownList.Items.Add("Blue")
MyDropDownList.Items.Add("Red")
MyDropDownList.Items.Add("Gray")
End If
End Sub
Public Sub Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim MyCookie As New HttpCookie("Background")
MyCookie.Value = MyDropDownList.SelectedItem.Text
response.write(mycookie.value)
MyCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(MyCookie)
End Sub
</script>
<html>
<body>
<form id="CookieForm" method="post" runat="server">
<asp:DropDownList id=MyDropDownList runat="server"/>
<asp:button id=MyButton runat="server" OnClick="Click"/>
</form>
</body>
</html>
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
<%@ Page Language="VB" %>
<script language="vb" runat="server">
Sub Page_Load(Source As Object, E as EventArgs)
Response.Cache.SetExpires(DateTime.Now)
End Sub
</script>
<html>
<body bgcolor="<%=Request.Cookies("Background").Value%>">
</body>
</html>
15
Download