request|response| Tips
Now, take a look at a few useful tips for using the request and response objects, including:
· Management of connections, buffering, and page redirection.
· HTTP headers, caching, and operations on the Expiration page.
· Take advantage of customer certificates.
· Create a custom log file message.
1. Connection, buffering and page redirection management
A useful feature of ASP is that it enables users to move from one ASP page to another (ASP or HTML), or another source file (such as a zip file or a text file). This is transparent to the user and is actually the browser doing the job. When you use the Response.Redirect method to load a new Web page, you are actually sending back a special HTTP header to the customer. This header is:
http/1.1 302 Object Moved
Location/newpath/newpage.asp
The browser reads this header information and loads the page as indicated by the location value. This is functionally the same as using the client html<meta> tag in a Web page, for example:
<meta http-equiv= "REFRESH" content= "0; Url=/newpath/newpage.asp ">
One problem with this is that the proxy server between the server and the user may provide its own message containing a link to the new page, rather than loading the new page directly. and browsers may do the same work according to the manufacturer and the version. This goes beyond the assumption of transparency, and the user is always receiving error messages, the access to your site becomes more cumbersome.
After any page content, such as text or HTML, is sent, we can no longer use the Redirect method. However, one way to look at limiting the "Proxy server impact" is to make sure that no output (including the HTTP header) is sent to the customer. In ASP 2.0, you must turn on buffering and then use the clear method to empty the buffer:
Response.Buffer = True
' Some condition to select the appropriate page:
If Request.ServerVariables ("server_port") = 1856 Then
Strnewpage = "/newpath/this_page.asp"
Else
Strnewpage = "/newpath/the_other_page.asp"
End If
Response.Clear
Response.Redirect strnewpage
In ASP 3.0, the buffer defaults to open, so the first line can be ignored, but it is harmless and ensures that our web pages still work even in the ASP 2.0 environment.
Rather than using this type of HTTP header redirection, a new feature of ASP 3.0, which allows us to convert from the transfer method of the server object to executing another Web page, will be further studied in chapter 4th.
1 ASP page Buffer
As has been seen, the ASP 3.0 page buffers in IIS 5.0 are open by default and are closed by default in earlier versions. Microsoft has told us that buffering provides more efficient Web delivery in IIS 5.0, which is why buffering defaults are changed. In most cases, this has no effect on us. However, if you have a very large web page, or a Web page that takes some time to create with ASP or other server-side code and components, when the parts are complete, we can refresh them in batches to the customer:
...
... Code to create the page
...
Response.Flush
...
... Code to create next part of page
...
Response.Flush
...
Sometimes you might want to stop the execution of your code at some point before the end of the page, and you can refresh all current content to the customer and abort any further processing by calling the ending method.
...
... Code to create the page
If strUserName = "" Then response.clear
...
... Code to create a new version of the page
...
Here are two instance pages that demonstrate buffering and redirection, which you can download from the Response Object home page (sow_response.asp). The first Response.Redirect example page is named Redirect.asp, which contains some content in the buffered page, clears the buffer, and redirects to another page:
For intloop = 1 to 1000000
Response.Write "."
Next
Response.Clear
Response.Redirect "Show_redirect.asp"
Response.End
The target page show_response.asp, doing the same job, but redirecting is back to the "Response Object" home page. Because these pages are in the buffer and all output must be cleared before redirection, there is no visible output in the browser. However, you can see each redirect that occurs by observing the state of the browser. As shown in the following illustration:
On the "Response Object" Home page, click "Response.Flush" The link opens the second example page usebuffer.asp, which simply traverses each character of a string and refreshes them to the customer with a certain delay, which is a very inefficient use of the Web server and ASP, but it demonstrates how buffering works.
Here is the minimized ASP code required, notice that we refresh each character to the browser separately, because otherwise it will be stored in the buffer until the Web page completes:
StrText = "This text has been flushed to the browser using" & _
"<B>Response.Flush</B>
”
For Intchar =1 to Len (StrText)
For intwrite = 1 to 100000
Next
Response.Write Mid (strtext,intchar,1)
Response.Flush
Next
2) Response.IsClientConnected Property
The IsClientConnected property already exists in ASP 2.0, but it is somewhat unreliable. Some output must be sent to the customer before it returns an accurate result. This problem has been resolved in ASP 3.0. This attribute is now free to use.
IsClientConnected is a useful way to observe whether a user is still connected to a server and is loading a Web page created by an ASP. If the user disconnects or stops downloading, we don't have to waste the server's resources creating the page because the buffer content will be discarded by IIS. Therefore, for those pages that require a lot of time to compute or use more resources, it is worth checking that the browser is offline at every stage:
...
... Code to create the page
...
If response.isclientconnected Then
Response.Flush
Else
Response.End
End If
...
... Code to create next part of page ...
1. Operation HTTP Header
We have seen in several places how ASPs Create or modify the HTTP headers that are sent to the customer in response to a page request. There are several properties and methods in the response object that can help us do a little. Here are some header methods:
· Controls caching and expiration.
· Creates a state and a custom HTTP header.
· Specifies the MIME type or content type.
· Add a Pics label.
The next step is to study each aspect briefly. On the Response Object home page (show_response.asp), click the related property name or method name to check the properties and methods that we said, as shown in the following illustration:
1. Cache and "Expiration" ASP Web pages
Users ' browsers, as well as their any proxy servers with servers, can cache HTML and Web pages created with ASP. When the user subsequently requests the page, the browser sends a "last modified" request to the server (using a http_if_modified_since header that contains the date of the cached version) to ask if the page has been modified.
If it is not modified, the server applies the status code and the message "304 not Modified" to respond, the browser will use the cached content instead of downloading a copy over the network. If a modified version already exists, it is sent with the "OK" status code and the message.
1) Response.cachecontol Property
Other factors can also affect the process. However, any proxy server within the network route used by the Web page (typically located on the client side) can be discarded by setting the Response.CacheControl property as private to discard the cached Web page. This is the default for ASP Web pages in ASP 3.0 and is not set. This is especially useful when web pages are specially tailored for individual visitors. This can prevent other users on the same network from entering the same Web page. Allows the server to cache Web pages when the CacheControl property value is set to public. Note that some proxy servers may behave differently, or ignore or bypass the header.
In IE4, it is possible to get a false "this page has expired" message when the proxy server cache is available. We have provided a Web page (expiretest_form.asp) that can be tested on the network through its own proxy server to check the impact of this property. You can click Response in the Response Object home page. CacheControl "link to display this page. As shown in the following illustration:
When this page is submitted to the Expiretest_result.asp Web page, you can set the Response.CacheControl property, and then insert the value in the Web page and the time the script was executed:
<%
If Request.Form ("public") = "on" Then ' cache-control check box is ticked
Response.CacheControl = "Public"
Else
Response.CacheControl = "Private"
End If
%>
<HTML>
...
Cache-control is: <b><% = Response.CacheControl%></b><p>
Value in text box is: <b><% Response.Write Request.Form ("textbox")%>
<%
Response.Write Right ("0" & Hour (now), 2) & ":" & Right ("0" & Minute (now), _
& 2) & ":" & Right ("0" & Second (now), 2)
%></b>
You can see whether the code executes automatically or uses a cached copy by clicking Back and Forward on the browser, as shown in the following illustration. The results vary depending on the browser.
2) Response.Expires and Response.ExpiresAbsolute properties
The two properties that control the cached Web page storage time are the expires and Expriesabsolute properties of the response object. Response.Expires defines the length of time that a wind page should remain valid before it is discarded from the buffer, in minutes that have been created. The ExpiresAbsolute property sets an absolute date and time for the expiration time.
We provide an example Web page named Addheaders_form.asp that demonstrates how to use these properties. In the Response Object home page, click the link to these two properties, as shown in the following illustration:
In this page, you can add your own custom HTTP headers and set several properties that affect the HTTP headers of the response. When you click on the Submit Query Content button, page show_headers.asp adds the selected header to the returned data stream, and then displays the code to complete the operation, showing the appropriate execution time to check whether the page is cached or executed again, as shown in the following illustration:
Show_headers.asp the code in the Web page creates and adds an HTTP header, as follows:
<%
' Write HTTP headers before any other output
If Request.Form ("expires") = "On" Then _
Response.Expires = Request.Form ("Expires_value")
If Request.Form ("expiresabs") = "On" Then _
Response.ExpiresAbsolute = Request.Form ("Expiresabs_value")
If Request.Form ("lastmod") = "On" Then _
Response.AddHeader "Last-modified", Cstr (Request.Form ("Lastmod_value"))
If Request.Form ("pragma") = "On" Then _
Response.AddHeader "PRAGMA", CStr (Request.Form ("Pragma_value"))
If Request.Form ("refresh") = "On" Then _
Response.AddHeader "REFRESH", CStr (Request.Form ("Refresh_value"))
If Request.Form ("addheader") = "on" and Len (Request.Form ("Addheader_name")) Then _
Response.AddHeader CStr (Request.Form ("Addheader_name")), _
CSTR (Request.Form ("Addheader_value"))
If Request.Form ("status") = "On" Then _
Response.Status = Request.Form ("Status_value")
%>
<HTML>
...
... Show code and execution time
...
The remainder shows only the code that has been executed and the execution time. Readers will notice the custom header "PRAGMA" included in the Web page (which we haven't discussed yet). Some (previous) proxy servers use it as an indication of whether the net magnetism should be cached. The default is that the Web page is buffered unless the HTTP header "Pragma=no-cache" is accepted.
2. Create a status code and a custom HTTP header
You can use the AddHeader method of the response object that you saw earlier in the instance Web page to create your own status code or your favorite custom header. This method requires two parameters: an HTTP header name or a string containing its value or the value assigned to it. As an example, the following code adds a refresh header to the page:
Response.AddHeader "REFRESH", "60; Url=newpath/newpage.asp "
This equates to the client side <META> elements:
<meta http-equiv= "REFRESH", "60; Url=newpath/newpage.asp "
In other words, you can also use the AddHeader method with the Status property to load a browser into a new page:
Response.Status = "302 Object moved"
Response.AddHeader "Location", "newpath/newpage.asp"
This equates to using the Response.Redirect method:
Response.Redirect "Newpath/newpage.asp"
The Response.Status property can be used to send some required status messages, such as adding the following lines:
Response.status= "401 Unauthorized"
Response.AddHeader "Www-authenticate", "BASIC"
Force the browser to display a username/password dialog box, and then use Basic authentication to send them back to the server (the validation method will be seen later in this book).
3. MIME type and content type
Response.ContentType is useful when we want to send a dynamically created string to the browser, and they provide the browser with no direct indication of the content type, but provide an extension that indicates whether it is a disk file. Unless specifically specified, all ASP-created Web pages are "Text/type" by default. The identifier for the content type is the MIME type (MIME represents multi-purpose Internet multimedia Extension or multi-pupose Internet Mail Extension, usually based on context).
For example, if a data annotation sent to a customer is a picture created by reading a binary value from a database, you need to add the appropriate Content-type header before any content is sent:
Response.ContentType = "Image/jpeg"
If you create an XML file from a database, use the Miem type "Text/xml", and if you are creating a text file that can be displayed in the file editor or stored as a disk file on the client, use "Text/text".
4. Add Pics Volume label
The Respnse.pics property is simply to add a pics (Platform for Internet Content System) volume to the page in the same way that you would normally use the <META> tag:
QUOT = Chr (34)
Strpicslabel = "(PICS-1.0" & QUOT & "Http://www.rsac.org/ratingsv01.html" _
& QUOT & "1 gen True Comment" & QUOT _
& "RSACi North America Server" & QUOT & "for" & QUOT _
& "Http://yoursite.com" & QUOT & "On" & QUOT _
& "1999.08.01t03:04-0500" & QUOT & "R (N 0 s 0 v 2 L 3))"
Response.PICS (Strpicslabel)
This code adds the following Pics volume label:
(PICS-1.0 "http://www.rsac.org/ratingsv01.html" 1 gen true comment "RSACi
North America Server ' for ' http://yoursite.com ' on ' 1999.08.01t03:04-0500 '
R (N 0 s 0 v 2 L 3))
To get more information about pics, or to learn more about how to define page content, please retrieve the http://www.rsac.org/site.
To define headers in Internet Service Manager
In the 1th chapter, you have explained how to set the properties of each Web site and IIS 5.0 directory in an Internet Service Manage (MMC) application, which defines the HTTP headers for all requests sent to the client using this site or directory resource. Also provides an alternative to using ASP script code in each Web page to set these properties.
Right-click on the Web site or directory and select Properties, in the HTTP Headers tab of its dialog box, you can set the relative time or absolute date of the page content validity period, define a custom header, create a Pics content level label, You can also define content types by using MIME type mappings, as shown in the following illustration:
In the illustration above, you can see that you have created a custom refresh HTTP header that applies to all pages that are loaded from this directory. That is, it is automatically overloaded (refreshed) once per minute (it is ideal for the recent score to show the baseball game, but it is too heavy for the server). The Edit dialog box for Custom HTTP headers columns is shown in the following illustration:
To add a custom content type mapping in the MIME Map box, simply click the File Types button in the Properties Main dialog box to add them to the manifest, as shown in the following illustration:
When you start experimenting with the HTTP header, you will soon find that not all browsers behave the same, and many browsers respond to different HTTP headers in different ways, making it sometimes extremely difficult to reliably establish a universally applicable principle.
2. Using a client certificate
If you have a secure Web site or some Web site with security in it, you can install a digital server certificate to authenticate the server by allowing visitors to use the details of the encryption in the certificate. Every time a page request is made to the site or directory, the server sends a copy of the certificate, which the browser can check to determine who is talking to.
Similarly, you can set up a server that requires users to provide a valid digital certificate when they enter the site. They can obtain this certificate from many sources, such as VeriSign (http://www.verisign.com) or Thawte Consulting (http://www.thawte.com). The reader will see the details of this process in chapter 25th.
These situations all use the value of the ClientCertificate collection of the Request object, which in this chapter contains a page that shows how users can use some of the collection values.
This page is named Showcert.asp, and all it does is traverse the ClientCertificate collection to display all the values it contains. It can be done using simple code that you used to use often, the only difference being to create an HTML table to hold the result and truncate it to a group of 60 characters.
<tabel cellpadding=0 cellspacing=0>
<%
For each keyitem in Request.clientcertificate ()
Stritemvalue = Request.clientcertificate (Keyitem)
If Len (stritemvalue) > Then stritemvalue = Left (Stritemvalue,) & "... etc. "
Response.Write "<TR><TD>" & keyitem & "=" & Stritemvalue & "</TD></TR>"
Next
%>
</TABLE>
The results of the operation are shown in the following illustration:
Using Client certificate redirection
Once all visitors to the site or part of the site are asked to give their client certificates, they can use the information they contain to make the pages we create for this user. For example, you can use the organization entry of their certificates to automatically redirect them to a specific part of the Web site so that other visitors redirect to another location:
If request.clientcertificate ("subjecto") = "Wrox Press INC" Then
Response.Redirect "/wrox_staff/default.asp" ' Wrox staff site
Else
Response.Redirect "/public/default.asp" ' Normal public site
End If
Accordingly, you can use the country entry to redirect the visitor to a corresponding Web site:
Select case Request.clientcertificate ("SUBJECTC")
Case "UK": Response.Redirect "http://uk_site.co.uk/"
Case "DE": Response.Redirect "http://de_site.co.de/"
Case "FR": Response.Redirect "http://fr_site.co.fr/"
' ... ect.
Case Else:Response.Redirect "http://us_site.com/"
End Select
3. Read and write binary data
There are two methods that provide binary data access to the HTTP data stream sent from the browser to the server and to the data stream returned from the server to the browser. The Request.BinaryRead method gets a parameter that specifies the number of bytes to read and returns an array of variant types that contains the bytes obtained from the post segment of the request (for example, data in the ASP's Form collection). The following program reads the first 64 bytes of data:
Varcontent = Request.BinaryRead (64)
If you use the BinaryRead method, you will not be able to access the ASP's Request.Form collection later. Similarly, once we have referenced the Request.Form collection in any way, we cannot use the BinaryRead method.
It is also possible to write binary data into the response stream created by ASP, and the BinaryWrite method can be used. An array of variant types that need to be given the byte to write to the customer:
Response.BinaryWrite (varcontent)
These methods are rarely used unless you create a non-HTML source from a database. One example of using is to read the bytes that make up the image from the database and send it to the customer using the BinaryWrite method.
4. Create a custom log message
If the server is set up and the request is logged to a text file in the Extended log file format format, you can use the Response.appendtolog method to add a message string at the end of the log files entry. This is useful if you want to store some values or messages for a particular Web page, or when a specific situation occurs in a script.
For example, the stationary order application for an intranet can record the department number of an employee exceeding a specific number of entries:
...
If intitemcount > Then
Response.appendtolog "Large order from" "& Strdept & Department."
End If
...
Set up the extended log
To use the AppendToLog method, you must activate the Extended log File format log setting. The setting method is to enter the Web Site tab in the Properties dialog box, select the Enable Logging checkbox, select the Extended Log File format and click the Properties button, as shown in the following illustration:
In the Extended Logging Properties dialog box that appears, you can select the entries you want to include in the log file. Make sure the URI Stem is selected or the AppendToLog method fails, as shown in the following illustration:
We provide a simple instance page that attempts to write an entry in the log file, which can be opened from the AppendToLog method link in the Request Object home page (show_request.asp). All the work on this page is to create a simple string containing the current date and time, and then execute the AppendToLog method:
Strtoappend = ' Page executed on ' & Now
Response.appendtolog Strtoappend
The results are shown in the following illustration:
Summary
This chapter has begun a study of ASP 3.0, and we have seen how ASP 3.0 works with Internet Informateion Server 5.0 to provide an easy-to-use and efficient way to create dynamic Web pages and Web applications. Of course, there are still some places to study, this chapter is just learning the ASP built-in two basic objects.
The two most basic objects are the request and response objects, which allow us to access and use values that are part of a client/server session, regardless of when a user requests and loads a page or resource from a Web site, the session takes place, means that the request object is able to provide access to all the content requested by the user, while the response object allows you to create and modify the response that the server sends back.
These objects can expose parts of a session through collections and attributes, and provide several methods that can be used to retrieve and modify segments. If you use them as a tool to break down user requests and create responses using the appropriate content, this can help you understand what's going on. This will also help you understand how various methods affect customers, servers, and Web pages that are being created.