AcceptTypes | |||||||||||||
stringArray = Request.AcceptTypes |
|||||||||||||
Returns a String array containing the Multipurpose Internet Mail Extension (MIME) types accepted by the client. You can use this property to determine whether a client can accept certain response types, including application types such as Word or Excel, which are supported only by Internet Explorer.The following table lists some common MIME types:
|
|||||||||||||
Parameters
|
|||||||||||||
Example | |||||||||||||
The code example declares a string array and an integer counter variable and assigns the AcceptTypes property value to the array variable. It then iterates the array members using the counter variable, writing each value to the browser by using the Message label control: Sub Page_Load( ) 'Display Accept Types Dim MyArray( ) As String Dim I As Integer MyArray = Request.AcceptTypes For I = 0 To MyArray.GetUpperBound(0) Message.Text &= "Type " & CStr(I) & ": " & CStr(MyArray(I)) & _ "<br/>" Next I End Sub |
|||||||||||||
The output of the code would look something like this: Type 0: image/gifType 1: image/x-xbitmap Type 2: image/jpeg Type 3: image/pjpeg Type 4: application/vnd.ms-powerpoint Type 5: application/vnd.ms-excel Type 6: application/msword Type 7: */* |
|||||||||||||
Notes | |||||||||||||
This property can prevent the server from wasting time sending responses to the client that the client cannot handle. For example, a request that would normally be fulfilled by returning an Excel spreadsheet could be fulfilled with an alternate response type for clients that do not support the Excel MIME type, application/vnd.ms-excel. |
ApplicationPath | |
stringvar = Request.ApplicationPath |
|
Returns a String containing the path to the virtual root of the current application. |
|
Parameters
|
|
Example | |
The code example retrieves the ApplicationPath and writes it to the client using the Message label control: Sub Page_Load( ) Message.Text = Request.ApplicationPath End Sub |
|
The output of the code should be the name of the virtual root of the application to which the request was sent. |
Browser | |
bc = Request.Browser |
|
Returns an instance of the HttpBrowserCapabilities class that describes the capabilities of the client browser. You can then use the class instance to determine what capabilities the client browser supports. The HttpBrowserCapabilities class exposes the capabilities of the client browser as a set of Boolean and String properties. Properties of the HttpBrowserCapabilities class include:
|
|
Parameters
|
|
Example
Sub Page_Load( ) Dim bc As HttpBrowserCapabilities bc = Request.Browser If bc.Cookies Then Message.Text = "Cookies are available with this browser" Else Message.Text = "Cookies are not available with this browser" End If End Sub |
|
Notes | |
You will probably use this property a lot if you plan to support multiple browsers and must provide the highest level of functionality on uplevel browsers such as Internet Explorer 5 or 6 or Netscape 6. For some properties, such as Cookies and JavaScript, the returned Boolean indicates only whether the browser version sending the request supports these features, not whether they are currently enabled in the current user's browser. This property is especially important when developing custom server controls, since it allows you to have your custom controls automatically tailor their output to a specific browser (or class of browsers). See Chapter 6 for more information on custom control development. |
ClientCertificate | |
cs = Request.ClientCertificate |
|
Returns an instance of the HttpClientCertificate class, which exposes information about the client security certificate settings. These properties include issuer information, key size, and certificate validity dates. |
|
Parameters
|
|
Example
Sub Page_Load( ) Dim cs As HttpClientCertificate cs = Request.ClientCertificate Message.Text = "Certificate Issuer is: " & cs.Issuer & "." End Sub |
|
Notes | |
You will probably use this property in intranet settings, where you have provided a limited set of clients with certificates (issued from your own Certificate Server) for accessing your application, rather than requiring them to authenticate by using a set of credentials entered via the browser. In this case, client certificates are mapped to NT user accounts to provide secure access. Client certificates can also be issued by trusted third parties, but this method is rarely used. If no client certificate is installed on the requesting client, this property returns an HttpClientCertificate instance with no valid property values. |
ContentEncoding | |
ce = Request.ContentEncoding |
|
Returns an instance of the Encoding class (located in the System.Text namespace), which represents the character encoding of the body of the current request. |
|
Parameters
|
|
Example | |
The example demonstrates how to display the current ContentEncoding to the user: Sub Page_Load( ) Dim ce As System.Text.Encoding ce = Request.ContentEncoding Message.Text = "Current encoding is: " & ce.EncodingName & "." End Sub |
|
For a request using UTF-8 content encoding, the output of this example would be: Current encoding is: Unicode (UTF-8). |
ContentLength | |
intvar = Request.ContentLength |
|
Returns an integer containing the length, in bytes, of the request sent from the client. This property includes only the content sent in the body of the HTTP request and does not include the length of the HTTP headers or of any data sent as part of an HTTP GET request (which would appear in the headers). If the HTTP request contains no body, its value is 0. |
|
Parameters
|
|
Example | |
This example demonstrates how to display the length of the current request in the browser: Sub Page_Load( ) Dim length As Integer length = Request.ContentLength Message.Text = "Length of request was: " & length & " bytes." End Sub |
|
The following code can be used to post to the example page: <html> <head> <title>Submit a named parameter via POST</title> </head> <body> <form id="form1" action="ContentLength.aspx" method="POST"> <h3>Name:</h3> <input type="text" name="name"> <input type="submit"> </form> </body> </html> |
|
Notes | |
You can use this property to test the length of content posted via a POST request before acting on that content. For example, if your page receives files from a file input field, you could check the ContentLength property before saving or processing the uploaded file to prevent users from uploading files greater than a specific size. Note that in cases when you receive multiple form fields, you can get more specific data on the size of an uploaded file by referring to the PostedFile.ContentLength property of an HtmlInputFile control used for submitting files. |
ContentType | |
stringvar = Request.ContentType |
|
Returns a String containing the MIME type of the current client request. On GET requests, this property may return an empty string. |
|
Parameters
|
|
Example | |
The example shows how you can take different actions in your page, depending on the ContentType of the request: Sub Page_Load( ) Dim ct As String ct = Request.ContentType If ct = "application/x-www-form-urlencoded" Then 'Process form input Message.Text = "Form data was submitted." Else Message.Text = "Content Type of request is: " & ct End If End Sub |
|
The following code can be used to post to the example page: <html> <head> <title>Submit a named parameter via POST</title> </head> <body> <form id="form1" action="ContentType.aspx" method="POST"> <h3>Name:</h3> <input type="text" name="name"> <input type="submit"> </form> </body> </html> |
|
Notes | |
One potential use for this property is to ensure that the content type of the request is what you expect it to be. This can help avoid wasting processor time with invalid requests and prevent malicious users from attempting to forge requests to your application that send unexpected content. |
FilePath | |
stringvar = Request.FilePath |
|
Returns a String containing the virtual path of the current client request. The virtual path includes the name of the application root folder, any subfolders in the request path, and the requested filename. |
|
Parameters
|
|
Example | |
The example displays the FilePath property to the user. Sub Page_Load( ) Dim fp As String fp = Request.FilePath Message.Text = "The virtual path of the current request is: _ & "<strong>" & fp & "</strong>" End Sub |
|
Notes | |
This property is identical to the Path property listed later in this chapter. |
HttpMethod | |
stringvar = Request.HttpMethod |
|
Returns a String containing the method (i.e., GET, POST, or HEAD) of the current request. |
|
Parameters
|
|
Example | |
The example uses the HttpMethod property to determine what action to take for a given request: Sub Page_Load( ) Select Case Request.HttpMethod Case "POST" Response.Write("POST requests not allowed!<br/>") Response.End Case "HEAD" Response.Write("HEAD requests not allowed!<br/>") Response.End Case "GET" 'Process request Message.Text = "GET requests are allowed!<br/>" Case Else Response.Write("Unknown request: not allowed!<br/>") Response.End End Select End Sub |
|
Note that we use Response.Write to send the message before calling Response.End. Calling Response.End will immediately terminate processing of the page, which will also prevent rendering of any server control output. The code for a page that makes a POST request to the example page is shown here: <html> <head> <title>Submit a named parameter via POST</title> </head> <body> <form id="form1" action="HttpMethod.aspx" method="POST"> <h3>Name:</h3> <input type="text" name="name"> <input type="submit"> </form> </body> </html> |
|
Notes | |
In classic ASP, the request method was typically retrieved using the REQUEST_METHOD key of the ServerVariables collection. Often, this key was used to create self-submitting form pages by displaying a set of form fields when the GET method was detected and processing the input received from the form fields when the POST method was detected. ASP.NET Web Forms provide built-in plumbing for self-submitting forms. By adding a form with the runat="server" attribute and adding one or more input type server controls to the form, the developer only needs to check the page's IsPostBack property to determine whether a POST or GET request has been received, and execute the desired code based on that property. |
InputStream | |
inputstream = Request.InputStream |
|
Returns a Stream object containing the body of the incoming HTTP request. |
|
Parameters
|
|
Example | |
The example uses a byte array to search for a specified character and then copies that character and the remaining contents of the stream to a string. The @Import directive shown in the example should be placed at the top of the page: <% @ Import Namespace="System.IO" %> Sub Page_Load( ) Dim InStream As Stream Dim iCounter, StreamLength, iRead As Integer Dim OutString As String Dim Found As Boolean InStream = Request.InputStream StreamLength = CInt(InStream.Length) Dim ByteArray(StreamLength) As Byte iRead = InStream.Read(ByteArray, 0, StreamLength) InStream.Close( ) For iCounter = 0 to StreamLength - 1 If Found = True Then OutString &= Chr(ByteArray(iCounter)) End If If Chr(ByteArray(iCounter)) = "A" Then Found = True OutString &= Chr(ByteArray(iCounter)) End If Next iCounter Message.Text = "Output:" & OutString End Sub |
|
The following code can be used to post to the example page: <html> <head> </head> <body> <form id="form1" action="InputStream.aspx" method="POST"> <h3>Name:</h3> <input type="text" name="name"> <input type="submit"> </form> </body> </html> |
|
The code returns as output the first capital A appearing in the request body. Any characters after it are returned to the end of the stream. |
|
Notes | |
This property is useful if you wish to perform byte-level filtering of the request body. It works only with POST requests, since these requests are the only commonly used HTTP requests that provide a request body. |
IsAuthenticated | |
boolvar = Request.IsAuthenticated |
|
Returns a Boolean indicating whether the current request is coming from a user who is authenticated. This property refers to authentication against the NTLM account database. |
|
Parameters
|
|
Example | |
The example checks to see if the current user is authenticated and it outputs one of two messages, depending on the authentication status of the user. Note that the message delivered to authenticated users utilizes the User property of the page to output the current user's name and domain. Sub Page_Load( ) Dim boolAuth As Boolean boolAuth = Request.IsAuthenticated If boolAuth Then Message.Text = "User" & Page.User.Identity.Name & "is authenticated." Else Message.Text = "Current user is not authenticated." End If End Sub |
|
Notes | |
In addition to the IsAuthenticated property that the HttpRequest class exposes, the FormsIdentity, WindowsIdentity, and PassportIdentity classes expose an IsAuthenticated property for much the same purpose as the HttpRequest class. Note that the IsAuthenticated property of the HttpRequest class returns the authentication status of the user regardless of the authentication method used. |
IsSecureConnection | |
boolvar = Request.IsSecureConnection |
|
Returns a Boolean indicating whether the current connection uses secure sockets (SSL) for communication. |
|
Parameters
|
|
Example | |
The example shows how you can take different actions depending on whether or not the current request was made via SSL: Sub Page_Load( ) Dim boolvar As Boolean boolvar = Request.IsSecureConnection If boolvar = True Then Message.Text = "Connection is HTTPS." Else Message.Text = "Connection is HTTP." End If End Sub |
|
Notes | |
You would typically use this property to determine whether or not to fulfill a request that requires an SSL connection in order to encrypt sensitive data (such as credit card numbers) that might be submitted via the requested page. Additionally, you could use this property on a page that may or may not use SSL to determine how to render output to the page depending on the SSL status. Since encrypting and decrypting content for SSL communication exacts a performance penalty, reducing the number and/or size of graphics used on SSL-enabled pages is generally considered good practice. With this property, you could render more and/or higher-resolution graphics when SSL is not enabled for the request, and render fewer and/or lower-resolution graphics for SSL requests. |
Path | |
stringvar = Request.Path |
|
Returns a String containing the virtual path of the current client request. The virtual path includes the name of the application root folder, subfolders in the request path, and the requested filename. |
|
Parameters
|
|
Example | |
The example displays the Path property to the user: Sub Page_Load( ) Dim path As String path = Request.FilePath Message.Text = "The virtual path of the current request is:" & path End Sub |
|
Notes | |
This property is identical to the FilePath property listed earlier in this chapter. |
PathInfo | |
stringvar = Request.PathInfo |
|
Returns a String containing any additional path information (including path information appended to a URL after the filename of the requested resource) passed with the current request. |
|
Parameters
|
|
Example | |
The example writes both the Path and PathInfo properties to the client browser: Sub Page_Load( ) Message.Text = "Path = " & Request.Path & "<br/>" Message.Text &= "Additional Path Info = " & Request.PathInfo & "<br/>" End Sub |
|
Notes | |
PathInfo does not return information such as query string values. PathInfo returns any characters following a forward-slash (/) after the resource (file) name, including the forward-slash itself. |
PhysicalApplicationPath | |
stringvar = Request.PhysicalApplicationPath |
|
Returns a String containing the physical path to the root of the current application. |
|
Parameters
|
|
Example | |
The example writes the PhysicalApplicationPath property to the browser: Sub Page_Load( ) Dim physAppPath As String physAppPath = Request.PhysicalApplicationPath Message.Text = "Physical Application Path = " & physAppPath End Sub |
|
Notes | |
This property is useful when you need to create or write to a file within your web application. Rather than hardcoding a filesystem path in your page, you can use this property in combination with a filename to create or edit a file in the same folder as the page containing the code, regardless of the page's location. |
PhysicalPath | |
stringvar = Request.PhysicalPath |
|
Returns a String containing the physical path to the requested file. |
|
Parameters
|
|
Example | |
The example writes the PhysicalPath property to the browser: Sub Page_Load( ) Dim physicalPath As String physicalPath = Request.PhysicalPath Message.Text = "Physical Path = " & physicalPath End Sub |
|
Notes | |
Unlike the PhysicalApplicationPath, which returns only the path to the root of the application, the PhysicalPath property returns the full physical path of the requested resource, including any intervening folders and the resource's filename. This property may be useful in combination with ASP.NET's Trace functionality in troubleshooting situations when files you are attempting to write to or read from are not found, or when created files aren't located where you expect them to be. Adding Trace.Write statements to your page to write the Path, PhysicalApplicationPath, and PhysicalPath properties to the trace log (which you can enable by adding the Trace="true" attribute to the @ Page directive) may help you track down such bugs. |
RawUrl | |
stringvar = Request.RawUrl |
|
Returns a String containing the raw URL of the current request. The raw URL consists of the portion of the URL following the domain information. Thus, for the URL http://search.support.microsoft.com/kb/c.asp, the raw URL is /kb/c.asp. The raw URL includes the query string, if one is present. |
|
Parameters
|
|
Example | |
The example writes the RawUrl property to the browser: Sub Page_Load( ) Dim stringvar As String stringvar = Request.RawUrl Message.Text = "The raw URL is:" & stringvar End Sub |
RequestType | |
stringvar = Request.RequestType |
|
The RequestType property returns a String containing the request type (i.e., GET or POST) of the current request. |
|
Parameters
|
|
Example | |
The example writes the RequestType property to the browser: Sub Page_Load( ) Dim stringvar As String stringvar = Request.RequestType Message.Text = "The request type is:" & stringvar End Sub |
|
Notes | |
This property is listed as read/write; however, there really aren't any situations where it would be useful to change its value. From the read standpoint, this property returns the same information as the read-only HttpMethod property listed earlier in this chapter. If you attempt to change its value, no corresponding change occurs in the value of HttpMethod. |
TotalBytes | |
intvar = Request.TotalBytes |
|
Returns an Integer representing the size of the HTTP request body. The TotalBytes property does not include the size of the HTTP request headers, or the size of query string values passed with a GET request. |
|
Parameters
|
|
Example | |
The example writes the TotalBytes property to the browser: Sub Page_Load( ) Dim intvar As Integer intvar = Request.TotalBytes Message.Text = "The size of the current request body is: <br/>" Message.Text &= intvar & "bytes." End Sub |
|
The following code can be used to post to the example page: <html> <head> <title>Submit a named parameter via POST</title> </head> <body> <form id="form1" action="TotalBytes.aspx" method="POST"> <h3>Name:</h3> <input type="text" name="name"> <input type="submit"> </form> </body> </html> |
|
Notes | |
This property's behavior is identical to that of the ContentLength property described earlier in this chapter. |
Url | |
uriObj = Request.Url |
|
Returns an instance of the Uri class containing properties that describe the current URL requested by the user. Properties exposed by the Uri class include Scheme (protocol), Port, and Host. |
|
Parameters
|
|
Example | |
The example uses the Uri object that the Url property returns to write information about the URL for the current request to the browser: Sub Page_Load( ) Dim myUri As Uri myUri = Request.Url Message.Text = "Current request URL info - <br/><br/>" Message.Text &= "Protocol:" & myUri.Scheme & "<br/>" Message.Text &= "Port:" & myUri.Port & "<br/>" Message.Text &= "Host Name:" & myUri.Host & "<br/>" End Sub |
|
Notes | |
While the Uri class this property returns has methods as well as properties, you're more likely to use these methods (particularly the CheckHostName and CheckSchemeName methods) when creating your own Uri resource from scratch, rather than when receiving the Uri instance from the Url property. A note on URIs: Uniform Resource Identifier (URI) (compare to Uniform Resource Locator, or URL) is a more general version of URLs and URNs. In most cases today, URI and URL are identical, although this may change as URNs are used more frequently. For the purposes of the Url property, the terms carry the same meaning. |
UrlReferrer | |
uriObj = Request.UrlReferrer |
|
Returns an instance of the Uri class containing properties that describe the URL for the resource from which the user navigated to the current requested resource. If the user did not navigate to the current resource (i.e., if the current resource is accessed directly), the UrlReferrer property returns Nothing. |
|
Parameters
|
|
Example | |
The example uses the Uri object that the UrlReferrer property returned in order to write information about the URL for the referring resource to the browser: Sub Page_Load( ) Dim myUri As Uri myUri = Request.UrlReferrer If Not (myUri Is Nothing) Then Message.Text = "Referral URL info - <br/><br/>" Message.Text &= "Protocol:" & myUri.Scheme & "<br/>" Message.Text &= "Port:" & myUri.Port & "<br/>" Message.Text &= "Host Name:" & myUri.Host & "<br/>" Message.Text &= "App Path:" & myUri.AbsolutePath & "<br/>" Else Message.Text = "No referral URL info available." End If End Sub |
|
The following code can link to the example page <html> <head> <title>Link to UrlReferrer</title> </head> <body> <a href="UrlReferrer.aspx">Go to UrlReferrer.aspx</a> </body> </html> |
|
Notes | |
The example code makes sure that the UrlReferrer property returns a valid instance of the Uri class. The UrlReferrer property returns Nothing if the page is accessed directly, rather than from a link on another page. |
UserAgent | |
stringvar = Request.UserAgent |
|
Returns a String containing the User-Agent header. The User-Agent string identifies the browser (or other HTTP-capable client software, such as that used on mobile phones, etc.) the client uses to make the request. Depending on the browser and platform, this string may also identify the operating system the client uses, as well as the version of the installed .NET Framework (IE only). |
|
Parameters
|
|
Example | |
The example writes the UserAgent property to the browser: Sub Page_Load( ) Dim stringvar As String stringvar = Request.UserAgent Message.Text = "User Agent:" & stringvar End Sub |
|
Notes | |
When you attempt to discern the capabilities of the client browser, using the properties of the HttpBrowserCapabilities object returned by the Request.Browser property is generally easier. However, there may be cases in which the User-Agent for a given client returns information that is not checked for by the HttpBrowserCapabilities class. In this case, you could add the desired information to the <browserCaps> configuration section handler in machine.config (see Chapter 8 and Chapter 20 for more information on ASP.NET configuration) and then create your own version of the HttpBrowserCapabilities class by inheriting from the built-in class and adding your own property or properties for the User-Agent attribute you're looking for. Or, if you don't want to make that effort, you could simply parse the User-Agent string for the desired attribute by using the UserAgent property. |
UserHostAddress | |
stringvar = Request.UserHostAddress |
|
Returns the IP address of the client making the request. |
|
Parameters
|
|
Example | |
The example writes the UserHostAddress, UserHostName, and UserLanguages properties to the browser: Sub Page_Load( ) Dim HostAddress, HostName, Languages( ) As String Dim iCounter As Integer HostAddress = Request.UserHostAddress HostName = Request.UserHostName Languages = Request.UserLanguages Message.Text = "Client IP Address:" & HostAddress & "<br/>" Message.Text &= "Client Machine Name:" & HostName & "<br/>" For iCounter = 0 To Languages.GetUpperBound(0) Message.Text &= "Client Language" & iCounter & ": " &_ CStr(Languages(iCounter)) & "<br/>" Next iCounter End Sub |
UserHostName | |
stringvar= Request.UserHostName |
|
Returns a string that contains the DNS hostname of the client making the request. |
|
Parameters
|
|
Example | |
See the example for the UserHostAddress property. |
|
Notes | |
If no DNS server is available that can resolve the client IP address to a DNS name, the UserHostName property returns the IP address of the client (just like the UserHostAddress property). |
UserLanguages | |
stringArray = Request.UserLanguages |
|
Returns a sorted String array containing the list of languages supported by the client. |
|
Parameters
|
|
Example | |
See the example for the UserHostAddress property. |
|
Notes | |
To test this property, you can set support for additional languages in your browser. Now if you browse a page containing the code in the UserHostAddress example, all languages you select will be listed in the order you chose.
|
|
Now if you browse a page containing the code in the UserHostAddress example, all languages you select will be listed in the order you chose. |
Cookies | |
HttpCookieCollection = Request.Cookies |
|
The Cookies collection returns an instance of the HttpCookieCollection class containing all cookies sent as a part of the current request. The HttpCookieCollection class contains an instance of the HttpCookie class for each cookie passed as part of the client request. The properties of these HttpCookie instances can be used to access information about the cookie(s). As in classic ASP, the Cookies collection is still implemented as a collection (in fact, the HttpCookieCollection inherits from the .NET NameObjectCollectionBase class), but rather than a collection of string keys and string values, the ASP.NET implementation is a collection of string keys and objects (instances of the HttpCookie class). Individual cookies are retrieved into variables of type HttpCookie, providing access to the cookies' values through class properties. Dictionary-style cookies (cookies with more than one value) are accessible through the Values property of the HttpCookie class, which returns a NameValueCollection containing the cookie subkeys and values. You can also retrieve individual values by their key with the following syntax: HttpCookie.Values(" keyname ") |
|
Parameters
|
|
Example | |
The example retrieves the collection of cookies from the Cookies property and writes out the key and value of each, along with any subkeys of dictionary cookies: Sub Page_Load( ) Dim Counter1, Counter2 As Integer Dim Keys(), SubKeys( ) As String Dim CookieColl As HttpCookieCollection Dim Cookie As HttpCookie ' Get Cookie collection CookieColl = Request.Cookies ' Get Cookie keys Keys = CookieColl.AllKeys ' Get cookies by index For Counter1 = 0 To Keys.GetUpperBound(0) Cookie = CookieColl(Keys(Counter1)) Message.Text = "Cookie:" & Cookie.Name & "<br/>" Message.Text &= "Expires: " & Cookie.Expires &"<br/>" ' Get keys for dictionary cookie into an array SubKeys = Cookie.Values.AllKeys ' Write dictionary cookie values to the browser For Counter2 = 0 To SubKeys.GetUpperBound(0) Message.Text &= "Key " & CStr(Counter2) + ": " &_ SubKeys(Counter2) & "<br/>" Message.Text &= "Value " & CStr(Counter2) + ": " &_ Cookie.Values(Counter2) & "<br/>" Next Counter2 Message.Text &= "<br/>" Next Counter1 End Sub |
|
Notes | |
The ASP implementation of the Cookies collection and the HttpCookieCollection class returned by the Cookies property expose a common set of properties; these properties are described in Section 16.3. While it is still possible in ASP.NET to retrieve an individual cookie by its text key as well as its numerical index, the differences in the operation make wholesale migration of ASP cookie-handling code to ASP.NET impractical without significant changes. For example, the following code will raise exceptions: For Each strKey In Request.Cookies Response.Write strKey & " = " &Request.Cookies(strKey) &_ "<br/>" If Request.Cookies(strKey).HasKeys Then For Each strSubKey In Request.Cookies(strKey) Response.Write "->"& strKey & "(" & strSubKey &_ ") = " &Request.Cookies(strKey)(strSubKey) & "<br/>" Next End If Next |
|
Apart from the fact that this code does not explicitly declare its variables or their types (both of which are required by default in ASP.NET), the previous code fails because the Request.Cookies(key) property returns an instance of HttpCookie, rather than a string, and the HttpCookie instance cannot be implicitly converted to a string for the Response.Write statement, which expects a string. Additionally, the call to Request.Cookies(key) does not get the subkeys for a dictionary cookie. Fortunately, the modifications necessary to make the previous code work are fairly simple and are shown here: For Each strKey In Request.Cookies Message.Text = strKey & " = " &_ Request.Cookies(strKey).ToString( ) & "<br/>" If Request.Cookies(strKey).HasKeys Then For Each strSubKey In Request.Cookies(strKey).Values Message.Text = "->"& strKey & "(" & strSubKey & _ ") = " & Request.Cookies(strKey)(strSubKey).ToString()_ & "<br/>" Next End If Next |
|
To solve the first issue, we use the HttpCookie's Value method to get the value of the cookie as a string. The solution to the second issue is to call the Values property of the HttpCookie instance, which allows us to retrieve the subkeys of a dictionary cookie. |
|
Another quirk of the change from the mostly text-based manipulation of cookie keys and values in ASP to class-based manipulation in ASP.NET is that the Expires property of the HttpCookie class is available whether you read or write to a cookie. In ASP, however, attempting to read the Expires property of a cookie would result in an error. Unfortunately, at the time of this writing, the Expires property of HttpCookie does not actually return the expiration of the cookie. Instead, it returns the value 12:00:00 AM, which suggests that despite its readability, the property is not designed to be read from. |
|
Finally, unlike classic ASP, the collections in ASP.NET are zero-based, so the first element in any collection or array is 0, not 1. This is especially important to remember when retrieving values by their index. |
Files | |
HttpFileCollection = Request.Files |
|
The Files collection, which is new to ASP.NET, returns a collection of type HttpFileCollection that contains any files uploaded by the user's current request. This collection is especially useful in combination with the HtmlInputFile Server Control, which provides the basic plumbing necessary to upload files via an HTTP POST request. When a user submits one or more files (one per HtmlInputFile control on the submitting page), you can retrieve the files by using the Files collection. |
|
Parameters
|
|
Example | |
The example uses two HtmlInputFile server controls and a server-side <script> block to upload files and process them. The example shows both the <form> section of the page and its controls and the <script> block containing the UploadBtn_OnClick method called by the onServerClick event of the HtmlInputButton control: <!--Place between the <head> and </head> tags --> <script runat="server"> Sub UploadBtn_Click(Sender as Object, e as EventArgs) UploadForm.Visible = False If InStr(Request.ContentType, "multipart/form-data") Then Dim Counter1 As Integer Dim Keys( ) As String Dim Files As HttpFileCollection ' Load File Files = Request.Files ' Get names of all files into an array Keys = Files.AllKeys For Counter1 = 0 To Keys.GetUpperBound(0) Message.Text &= "File ID: " & Keys(Counter1) & "<br/>"_ Message.Text &= "File Name/Path: " &_ Files(Counter1).FileName & "<br/>" Next Counter1 Else Message.Text = "Wrong content type!" End If End Sub </script> <!-- This section resides between the <body> and </body> tags --> <form id="UploadForm" enctype="multipart/form-data" runat="server"> Select File To Upload to Server: <br/> <%-- MyFile and MyFile2 are HtmlInputFile controls --%> <%-- note the runat attribute --%> <input id="MyFile" type="file" runat="server"> <br/> <input id="MyFile2" type="file" runat="server"> <br/> <input id="Submit1" type="submit" value="Upload!" onserverclick="UploadBtn_Click" runat="server" > </form> <asp:label id="Message" runat="server"/> |
|
Notes | |
In classic ASP, file uploading was a painful process that usually involved finding and purchasing a third-party upload control to use on the receiving ASP page to parse and save uploaded files. Thanks to the Files collection, you no longer need to locate and learn how to use third-party controls to upload files. This is bad for the control developers (although we suspect they'll more than make up for the loss by writing new Server Controls), but great for ASP.NET developers. Two important points to remember about the Files collection to successfully upload files:
|
|
The upload will succeed only if you take both steps. Note that the code example checks to see if the incoming request is multipart/form-data before attempting to retrieve the files. |
|
It is not necessary to use the HtmlInputFile control to upload files that can be retrieved via the Files collection. As long as the submitting page uses the POST method and the multipart/form-data enctype attribute, you can use the standard HTML file input tags: <input type="file" id="myFile" name="myFile"> |
|
Note the use of the name attribute, without which the files collection will not contain the uploaded file for the control. |
Form | |
NameValueCollection = Request.Form |
|
The Form collection returns an instance of the NameValueCollection class containing all form fields passed along with an HTTP POST request. This collection will contain data only when the Content-Type of the HTTP request is either application/x-www-form-urlencoded or multipart/form-data. The Form collection is one of two ways to retrieve data, depending on the HTTP method used to submit the data. The Form collection retrieves data submitted by an HTML form whose method attribute is set to POST , while the QueryString collection (covered later in this section) retrieves values submitted by HTML forms whose method attribute is set to GET. |
|
Parameters
|
|
Example | |
The example demonstrates how ASP.NET allows a single page to be used to submit values via HTTP POST and retrieve and display the values to the user. The example uses the IsPostBack property of the Page class to determine whether the request is a result of the form being submitted. If the request is not a postback, the form fields are displayed to allow the user to enter values. If the request is a postback, the page retrieves the Form collection and displays the name and value of each field in the browser. Sub Page_Load( ) If IsPostBack Then Form1.Visible = False If Request.HttpMethod= "POST" Then Dim Counter1 As Integer Dim Keys( ) As String Dim FormElements As NameValueCollection ' Get Form keys/elements FormElements=Request.Form ' Get names of form fields into array Keys = FormElements.AllKeys For Counter1 = 0 To Keys.GetUpperBound(0) Message.Text &= "Form " & Counter1 & " name: " &_ Keys(Counter1) & " <br/>" Message.Text &= "Form " & Counter1 & " value: " &_ FormElements(Counter1) & "<br/>" Next Counter1 End If Else Form1.Visible = True End If End Sub <!-- This section resides between the <body> and </body> tags --> <form id="Form1" runat="server"> First Name: <br/> <asp:Textbox id="txtFName" runat="server"/> <br/> Last Name: <br/> <asp:Textbox id="txtLName" runat="server"/> <br/> <asp:Button id="Submit" Text="Submit" runat="server"/> </form> <asp:label id="Message" runat="server"/> |
|
Notes | |
The Form collection exposes the same properties and methods described in Section 16.3 and adds the following methods:
|
Headers | |
NameValueCollection = Request.Headers |
|
The Headers collection returns an instance of the NameValueCollection class containing all HTTP headers sent with the current request. This collection provides the same information that is returned by calling the Request.ServerVariables collection with the ALL_HTTP key. |
|
Parameters
|
|
Example | |
The example writes the HTTP headers passed with the request to the browser, first by using the ServerVariables("ALL_HTTP") method and then by using the Headers collection: Sub Page_Load( ) Dim AllHttp As String ' Get a String with all the HTTP headers AllHttp = Request.ServerVariables("ALL_HTTP") ' Use Replace to format the String AllHttp = Replace(AllHttp, "HTTP", " <br/>HTTP" Message.Text &= AllHttp & "<br/><br/>" Dim Counter1, Counter2 As Integer Dim Keys(), subKeys( ) As String Dim HeaderColl As NameValueCollection ' Load Headers into NameValueCollection HeaderColl=Request.Headers ' Get keys into an array Keys = HeaderColl.AllKeys For Counter1 = 0 To Keys.GetUpperBound(0) Message.Text &= "Key: " & Keys(Counter1) & "<br/>" ' Get all values under this key subKeys = HeaderColl.GetValues(Counter1) For Counter2 = 0 To subKeys.GetUpperBound(0) Message.Text &= "Value " & CStr(Counter2) & ": " &_ subKeys(Counter2) & "<br/>" Next Counter2 Next Counter1 End Sub |
|
Notes | |
The Headers collection returns only the HTTP headers that were sent as a part of the current request, as opposed to the ServerVariables collection (described later in this section), which contains keys for every HTTP header, regardless of whether a value was passed. If all you need to do is write the HTTP headers to a file or display them in the browser, it may be simpler to use the ServerVariables collection. In cases when you need to access a specific HTTP header by name or loop through the collection, the Headers collection is the way to go. |
Params | |
NameValueCollection = Request.Params |
|
The Params collection returns an instance of the NameValueCollection class containing key/value pairs for the QueryString, Form, ServerVariables, and Cookies collections. You can use the Params collection to dump all of these collections to a file or to the browser and to troubleshoot an application or track the form values your application receives, regardless of whether they come via GET (QueryString collection) or POST (Form collection). |
|
Parameters
|
|
Example | |
The example writes the keys and values contained in the Params collection to the browser: Sub Page_Load( ) Dim Counter1, Counter2 As Integer Dim Keys(), subKeys( ) As String Dim ParamColl As NameValueCollection ' Load Params into NameValueCollection ParamColl=Request.Params ' Get keys into an array Keys = ParamColl.AllKeys For Counter1 = 0 To Keys.GetUpperBound(0) Message.Text &= "Key: " & Keys(Counter1) & "<br/>" ' Get all values under this key subKeys = ParamColl.GetValues(Counter1) For Counter2 = 0 To subKeys.GetUpperBound(0) Message.Text &= "Value " & CStr(Counter2) & ": " &_ subKeys(Counter2) & "<br/>" Next Counter2 Message.Text &= "<br/>" Next Counter1 End Sub |
|
The following code can be used to post to the example page: <html> <head> <title>Submit a named parameter via POST</title> </head> <body> <form id="form1" action="Params.aspx" method="POST"> <h3>Name:</h3> <input type="text" name="name"> <input type="submit"> </form> </body> </html> |
|
Notes | |
The collections are listed in the following order:
|
|
While it is possible to have both the Form and QueryString collections populated (for example, if a query string name/value pair is added to the URL for the action attribute of a form by us. |
QueryString | ||||||||||||
NameValueCollection = Request.QueryStrings |
||||||||||||
The QueryString collection returns an instance of the NameValueCollection class containing all the keys and values passed as a part of the query string (typically by submitting an HTML form that uses the GET method instead of POST). |
||||||||||||
Parameters
|
||||||||||||
Example | ||||||||||||
The example writes the contents of the QueryString collection to the browser: Sub Page_Load( ) Dim Counter1, Counter2 As Integer Dim Keys(), subKeys( ) As String Dim QSColl As NameValueCollection ' Load QS into NameValueCollection QSColl=Request.QueryString ' Get keys into an array Keys = QSColl.AllKeys For Counter1 = 0 To Keys.GetUpperBound(0) Message.Text &= "Key: " & Keys(Counter1) & "<br/>" subKeys = QSCol1.GetValues(Counter1) 'Get all values under this key For Counter2 = 0 To subKeys.GetUpperBound(0) Message.Text &= "Value " & CStr(Counter2) & ": " & _ subKeys(Counter2) & "<br/>" Next Counter2 Message.Text &= "<br/>" Next Counter1 End Sub |
||||||||||||
The following code can be used to post to the example page (note that the form method attribute has been set to GET, which is required for the form value to be sent as part of the query string): <html> <head> <title>Submit a named parameter via POST</title> </head> <body> <form id="form1" action="QueryString.aspx" method="GET"> <h3>Name:</h3> <input type="text" name="name">" <input type="submit"> </form> </body> </html> |
||||||||||||
Notes | ||||||||||||
One advantage that the QueryString collection has over the Form collection is that you do not always need to have the user submit a form to use it. Because the query string values are appended to the URL, it is relatively simple to statically add query strings to links within pages or dynamically create anchor tags with query string values appended. In fact, many online stores use this method to drive their catalog pages (by passing a product ID appended onto a link to the page designed to display the product). That page can then retrieve the ID by using the QueryString collection. |
||||||||||||
Because query string values are passed as plain text appended to the URL, they are more vulnerable to tampering than values passed as a result of a POST operation. If you need to pass important data or data that, if tampered with, could create problems for your application, you should consider encrypting values before adding them to the query string or using another method to pass the values |
||||||||||||
Certain characters used in query string processing, including &, ?, %, and +, must be encoded to avoid confusion between their use in your key/value pair and their role as special characters in a query string. The following table lists the encoding for each of these special characters:
|
||||||||||||
Rather than memorizing these values, you could make your life easier by simply using the UrlEncode method provided by the HttpServerUtility class (covered in Chapter 18), which automatically substitutes the appropriate encoding for any special characters in a string passed to it. |
ServerVariables | |
NameValueCollection = Request.ServerVariables |
|
Parameters
|
|
Example | |
The example, as in the previous collection-related examples, writes the contents of the ServerVariables collection to the browser: Sub Page_Load( ) Dim Counter1, Counter2 As Integer Dim Keys(), subKeys( ) As String Dim SVarsColl As NameValueCollection ' Load ServerVariables into NameValueCollection SVarsColl=Request.ServerVariables ' Get keys into an array Keys = SVarsColl.AllKeys For Counter1 = 0 To Keys.GetUpperBound(0) Message.Text &= "Key: " & Keys(Counter1) & "<br/>" subKeys = SVarsColl.GetValues(Counter1) ' Get all values under this key For Counter2 = 0 To subKeys.GetUpperBound(0) Message.Text &= "Value " & CStr(Counter2) & ": " & _ subKeys(Counter2) & "<br/>" Next Counter2 Message.Text &= "<br/>" Next Counter1 End Sub |
|
Notes | |
In addition to retrieving all the values by looping through the Keys, you can access individual values if you know their key. The following list shows the available keys for the ServerVariable collection:
|
BinaryRead | |
byteArray = Request.BinaryRead(byteCount) |
|
Returns a byte array containing the number of bytes specified by the byteCount argument. |
|
Parameters
|
|
Notes | |
This method provides backward compatibility with classic ASP applications. For new development, using other means (such as the Files collection, etc.) is preferable to achieve the results that this method was used for. |
MapPath | |
stringvar = Request.MapPath(virtualPath) stringvar = Request.MapPath(virtualPath, _ baseVirtualDirectory, allowCrossMapping) |
|
The MapPath method, which the Server object exposed in classic ASP, allows you to retrieve a physical path on the server for a provided virtual path. In ASP.NET, this method is overloaded, meaning that it can be called with two different sets of arguments, as shown in the previous code. The first style, which is the same as in classic ASP, simply passes in a String containing the virtual path to be mapped. The second adds the baseVirtualDirectory argument, which specifies a base from which to resolve relative paths, and the allowCrossMapping argument, which allows you to map virtual paths that belong to other applications. |
|
Parameters
|
|
Example | |
The example maps the path of the .NET Framework SDK samples' /QuickStart directory and writes the result to the browser: Sub Page_Load( ) Dim VirPath, PhysPath, BasePath As String Dim BoolCross As Boolean = True VirPath = "/QuickStart" BasePath = "" Message.Text = Request.MapPath(VirPath, BasePath, BoolCross) End Sub |
|
Notes | |
In the previous example, if we had set the BoolCross variable to False and called the example code from outside the QuickStart application, an HttpException would be thrown, since this argument must be set to True to map paths across applications. |
SaveAs | |
Request.SaveAs(filename, includeHeaders) |
|
Saves the current HTTP request to disk, using the filename argument as the path and filename under which to save the request |
|
Parameters
|
|
Example | |
The example writes the HTTP request headers to the browser (for comparison purposes) and then saves the current request both with and without header information: Sub Page_Load( ) Message.Text = Request.Headers ' Save HTTP Request and Headers to a file Request.SaveAs((Request.PhysicalApplicationPath & _ "HTTPRequest.txt"), True) ' Save HTTP Request to a file Request.SaveAs((Request.PhysicalApplicationPath & _ "HTTPRequest_NoHeaders.txt"), False) End Sub |
|
Notes | |
This method can be very useful when debugging because it allows you to look at all the information sent in a given request (which is particularly useful in POST requests). |