[ Team LiB ] |
16.2 Properties Reference
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:
Parameter
ExampleThe 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:
NotesThis 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.
Returns a string containing the path to the virtual root of the current application. Parameter
ExampleThe 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.
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:
Parameter
ExampleSub 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 NotesYou 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.
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. Parameter
ExampleSub Page_Load( ) Dim cs As HttpClientCertificate cs = Request.ClientCertificate Message.Text = "Certificate Issuer is: " & cs.Issuer & "." End Sub NotesYou 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.
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. Parameter
ExampleThe 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).
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. Parameter
ExampleThis 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> NotesYou 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 Posted-File.ContentLength property of an HtmlInputFile control used for submitting files.
Returns a string containing the MIME type of the current client request. On GET requests, this property may return an empty string. Parameter
ExampleThe 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> NotesOne 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.
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. Parameter
ExampleThe 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 NotesThis property is identical to the Path property listed later in this chapter.
Returns a string containing the method (i.e., GET, POST, or HEAD) of the current request. Parameter
ExampleThe 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 procfessing 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> NotesIn 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.
Returns a stream object containing the body of the incoming HTTP request. Parameter
ExampleThe 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. NotesThis 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.
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. Parameter
ExampleThe 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 NotesIn 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.
Returns a Boolean indicating whether the current connection uses secure sockets (SSL) for communication. Parameter
ExampleThe 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 NotesYou 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.
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. Parameter
ExampleThe 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 NotesThis property is identical to the FilePath property listed earlier in this chapter.
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. Parameter
ExampleThe 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 NotesPathInfo 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.
Returns a string containing the physical path to the root of the current application. Parameter
ExampleThe 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 NotesThis 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.
Returns a string containing the physical path to the requested file. Parameter
ExampleThe 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 NotesUnlike 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.
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. Parameter
ExampleThe 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
The RequestType property returns a String containing the request type (i.e., GET or POST) of the current request. Parameter
ExampleThe 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 NotesThis 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.
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. Parameter
ExampleThe 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> NotesThis property's behavior is identical to that of the ContentLength property described earlier in this chapter.
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. Parameter
ExampleThe 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 NotesWhile 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.
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. Parameter
ExampleThe 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> NotesThe 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.
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.) that 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). Parameter
ExampleThe 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 NotesWhen 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 Chapters 8 and 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.
Returns the IP address of the client making the request. Parameter
ExampleThe 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
Returns a string that contains the DNS hostname of the client making the request. Parameter
ExampleSee the example for the UserHostAddress property. NotesIf 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).
Returns a sorted string array containing the list of languages supported by the client. Parameter
ExampleSee the example for the UserHostAddress property. NotesTo test this property, you can set support for additional languages in your browser as follows:
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. |
[ Team LiB ] |