DekGenius.com
[ Team LiB ] Previous Section Next Section

17.2 Properties Reference

Buffer

Boolean = Response.Buffer
Response.Buffer = Boolean

Returns or sets a Boolean value that represents whether output is buffered on the server and sent when the request has completely finished processing, or when either the Response.Flush or Response.End methods are called. The default value is True.

Parameter

Boolean

A Boolean that will receive or set the value of the property.

Notes

This property is supplied for backward compatibility with classic ASP and has been deprecated in favor of the BufferOutput property. New ASP.NET code should use BufferOutput in place of Buffer.

One important difference between the Response.Buffer property in classic ASP and the Buffer and BufferOutput properties in ASP.NET is that in classic ASP, you could not modify the Buffer property beyond the point at which output had been sent to the browser without causing an error. In ASP.NET, because of its compiled (rather than interpreted) nature, you can modify the Buffer or BufferOutput property at any time, and the change only affects how buffering occurs. This gives developers much more flexibility over how and when their output is buffered. See the BufferOutput example for a demonstration.

BufferOutput

Boolean = Response.BufferOutput
Response.BufferOutput = Boolean

Returns or sets a Boolean value that represents whether output is buffered on the server and sent when the request has completely finished processing, or when either the Response.Flush or Response.End methods are called. The default value is True.

Parameter

Boolean

A Boolean that will receive or set the value of the property.

Example

The example sets the BufferOutput property to False and then loops 50 times, writing a period to the HTTP output with each loop iteration. It also writes the same output to the Text property of the Message Label control. For the first 10 and the last 21 iterations, BufferOutput is set to False; for iterations 11 through 29, it is set to True.

Sub Page_Load( )
   Response.BufferOutput = False
   Dim i As Integer
   For i = 1 To 50
      If (i > 10 And i < 30) Then 
         Response.BufferOutput = True
      Else
         Response.BufferOutput = False
      End If
      System.Threading.Thread.Sleep(500)
      Response.Write(".")
      Message.Text &= "."
      'Response.Flush
   Next
   Response.Write("<br/>Done!<br/>")
   Message.Text &= "<br/>Done!<br/>"
End Sub

The output of the code would look something like this:

.................................................. Done! ................ 
.................................. Done!

The first line of periods should appear one by one until 10 have appeared, then pause, and then 20 more should appear, followed one by one by the rest and finally by the "Done!" statement. The identical output produced by the ASP.NET Label control (as an HTML <span>) will appear at once, since the output of controls on the server is not sent to the client until the control is rendered. This means that for each loop in the example, the code simply adds to a property of the control that will be rendered at a later time, while the text sent by the call to Response.Write is sent to the browser immediately after buffering is turned off.

You can see similar behavior by commenting out the Response.BufferOutput lines in the example (by prepending a single-quote (') character to the line), and uncommenting the Response.Flush line. This commenting and uncommenting will eliminate the pause in the output described previously.

The call to the Shared (static) Thread.Sleep method allows us to pause processing of an ASP.NET request for a given number of milliseconds. This can be useful when you need to wait during processing for whatever reason. However, using this method can impact the total time each request takes to process. In applications requiring high scalability, this may result in an unacceptable impact on the overall throughput of the application, since only a limited number of threads are available to process requests.

To avoid explicitly providing the namespace name when calling Thread.Sleep, add the following line to the page, immediately following the @ Page declaration:

<%@ Import Namespace="System.Threading" %>

Notes

This property is the ASP.NET equivalent of classic ASP's Buffer property and is preferred over Buffer for new development.

Cache

HttpCachePolicy = Response.Cache

Returns an instance of the HttpCachePolicy class that contains the cache policy of the page. You can use the methods exposed by the HttpCachePolicy class with this class instance to examine which headers or parameters (if any) have been set to vary the output cache, or to modify the current cache settings. The HttpCachePolicy class includes the following members:

HttpCachePolicy member

Description

SetCacheability method

Controls caching by setting the HTTP Cache-Control header.

SetExpires method

Sets the HTTP Expires header. This method takes a DateTime argument that represents the absolute expiration time for the header.

SetLastModified method

Sets the HTTP Last-Modified header. This method takes a DateTime argument that represents the absolute expiration time for the header.

Insert method

Inserts an item into the cache and assigns it a key.

Item property

Returns an Object representing a cache item based on its key value or sets an item of data in the cache while assigning it a key value.

Remove method

Removes an item with a particular key value from the cache.

Parameter

HttpCachePolicy

An Object variable of type HttpCachePolicy.

Example

The example retrieves an instance of the HttpCachePolicy class into a local variable, sets the expiration time to two minutes after the page is processed, and then sets the cacheability of the of the page to Public. Finally, the Text property of the Message label control is set to the current time.

Sub Page_Load( )
   Dim myCachePol As HttpCachePolicy
   myCachePol = Response.Cache
   myCachePol.SetExpires(DateTime.Now.AddSeconds(120))
   myCachePol.SetCacheability(HttpCacheability.Public)
   Message.Text = Now.ToString( )
End Sub

The output of the page should be the current date and time. If refreshed, the output should not change until two minutes have elapsed.

Notes

The HttpCachePolicy object returned by this property is the preferred method in ASP.NET for modifying the cache policy for a given page. HttpCachePolicy provides the functionality provided by the classic ASP CacheControl, Expires, and ExpiresAbsolute properties. For example, the HttpCachePolicy class allows you to explicitly prevent the server from caching the response in question, but still allows downstream caching of the response.

You can also set the output caching policies for a page through the @ OutputCache directive and its attributes, although this provides less granular control than that provided by the methods of the HttpCachePolicy class. Caching through the @ OutputCache directive is discussed in Chapter 3.

CacheControl

Response.CacheControl = String

Sets the cacheability of the current page.

Parameter

String

A string variable containing the value to set for the CacheControl property. Valid values include "Public" and "Private".

Example

Sub Page_Load( )
   Response.CacheControl = "Public"
   Response.Expires = 2
   Message.Text = Now.ToString( ) 
End Sub

The output of the code above should be identical to the previous example.

Notes

This property has been deprecated in favor of the HttpCacheability class methods.

Charset

String = Response.Charset
Response.Charset = String

Returns or sets a string representing the character set of the current response. When explicitly set, the value assigned to the Charset property is added to the HTTP Content-Type response header.

Parameter

String

A string variable to receive or set the value of the property. The default is UTF-8.

Example

The example below sets the character set for the HTTP response to Windows-1255 (note that as the name suggests, this character set is only available on Internet Explorer on Windows clients and may cause other browsers or browsers on other operating systems to display the page incorrectly). It then writes the value of the character set to the Text property of the Message label control. To see the difference between this character set and the default UTF-8 character set, load the page into Internet Explorer, and comment out the line that sets the Charset property, save the page, and reload it in the browser.

Sub Page_Load( )
   Response.Charset = "Windows-1255"
   Message.Text = "Current character set is " & Response.Charset
End Sub

Notes

Attempting to modify this property after the HTTP headers are sent to the browser results in an HttpException being thrown. This would most likely occur if you disabled output buffering by using the BufferOutput property and then wrote content to the browser by using Response.Write.

If the character set specified by the Charset property is not valid for the browser used by the client, it will be ignored and the default character set for that browser will be used instead. As mentioned above, using the default character set may cause the page to be displayed differently than intended.

ContentEncoding

Encoding = Response.ContentEncoding
Response.ContentEncoding = Encoding

Returns an instance of the Encoding class representing the encoding of the current response. The Encoding class exposes properties and methods that allow you to examine and modify the system's character encoding—i.e., the way in which characters are stored internally in the system. For example, you can convert a Unicode string to ASCII, UTF-7, or UTF-8.

Parameter

Encoding

An Object variable of type Encoding. Its EncodingName property provides the human-readable name of the encoding type.

Example

The example uses the properties of the Encoding class instance returned from the ContentEncoding property to display the human-readable name and the registered (IANA) name of the current encoding:

Sub Page_Load( )
   Message.Text = "Current encoding is " & _
      Response.ContentEncoding.EncodingName & "<br/>"
   Message.Text &= "Current encoding IANA name is " & _
      Response.ContentEncoding.WebName & "<br/>" 
End Sub

Notes

The ContentEncoding property is new in ASP.NET and provides a richer interface for examining and modifying character set and code page information for the current response. It also provides the only way to convert one character-encoded string to another character encoding (i.e., Unicode to ANSI).

ContentType

String = Response.ContentType
Response.ContentType = String

Returns or sets a string containing the MIME type of the current response. This allows you to retrieve or set the value of the HTTP Content-Type response header.

Parameter

String

A string variable to receive or set the content type. The default is "text/html".

Example

The following example displays the current MIME content type in the client browser:

Sub Page_Load( )
   Message.Text = "Current content type is " & _
      Response.ContentType & "<br/>" 
End Sub

Notes

The ContentType property is very important, since it enables you to send content to the client browser other than the default HTML. For example, if you want to use the Response.BinaryWrite method to send binary image data to the client browser, you must also set the ContentType property to the appropriate MIME type ("image/jpg" or "image/gif", for example). See the BinaryWrite example for an example of how this is done.

Expires

Integer = Response.Expires
Response.Expires = Integer

Returns or sets an integer representing the number of minutes before a cached page expires. This property is used in concert with the CacheControl property to control caching of responses.

Parameter

Integer

An Integer variable to receive or set the expiration in minutes.

Notes

This property is provided for backward compatibility with classic ASP. It has been deprecated in favor of the methods of the HttpCachePolicy instance returned by the Cache property.

ExpiresAbsolute

DateTime = Response.Expires
Response.Expires = DateTime

Returns or sets a DateTime value representing the date and time at which a cached response should expire.

Parameter

DateTime

A DateTime variable to receive or set the absolute expiration.

Example

The following example makes the current response cacheable by using the CacheControl property and then sets the absolute expiration to 30 seconds from the current time:

Sub Page_Load( )
   Response.CacheControl = "Public"
   Response.ExpiresAbsolute = DateTime.Now.AddSeconds(30)
   Message.Text = Now.ToString( ) 
End Sub

Notes

This property is provided for backward compatibility with classic ASP. It has been deprecated in favor of the methods of the HttpCachePolicy instance returned by the Cache property.

IsClientConnected

Boolean = Response.IsClientConnected

Returns a Boolean indicating whether the client is still connected. Returns False if the client is no longer connected.

Parameter

Boolean

A Boolean variable to receive the value of the property.

Example

The example checks the IsClientConnected property before starting a long-running processing task in order to avoid the expense of running the task if the client is no longer connected. If the property returns False, the code calls the Response.End method. Even though the client has disconnected and can no longer receive the buffered output (which is sent when the End method is called), calling the End method is still a good idea, since it will halt further processing of the page and fire the Application_EndRequest event. If you have written cleanup code for the page that is run by the event handler for Application_EndRequest, calling Response.End will ensure that the cleanup code is executed, even if the client disconnects.

Sub Page_Load( )
   'Check client connection status
   If Response.IsClientConnected = False Then
      Response.End
   Else
      'Start long-running processing task
   End If
End Sub

Notes

The IsClientConnected property is especially useful for long-running processes that require a significant amount of processing resources on the server. By querying the IsClientConnected property before starting an expensive processing task, or by querying the property periodically during processing, you can bypass further processing if the client has disconnected for some reason.

Output

TextWriter = Response.Output

Returns a write-only TextWriter object that can be used to write text directly to the output stream of the current response.

Parameter

TextWriter

An Object variable of type TextWriter. The TextWriter class includes the following members:

Member

Description

Close method

Closes the text writer and releases its resources.

Flush method

Clears the text writer's buffer and writes output to its underlying device.

NewLine property

Gets or sets the new line character(s) used by the TextWriter object.

Write method

Writes data to the text stream.

WriteLine method

Writes data followed by a newline character to the text stream. The NewLine property defines the newline character.

Example

The example declares a local variable of type TextWriter, retrieves an instance of TextWriter from the Output property, and then uses the WriteLine method to write the text "Hello, World!" to the output stream. The WriteLine method writes the specified text (or text representation of nonstring data types), along with a line terminator, specified by setting the NewLine property of the TextWriter. Without setting the NewLine property, the line terminator would affect the formatting of the text sent to the browser. However, it would not alter the formatting of the output as rendered by the browser, since browsers typically ignore whitespace such as non-HTML line terminators when rendering HTML.

Sub Page_Load( )
   Dim myWriter As System.IO.TextWriter
   myWriter = Response.Output
   myWriter.NewLine = "<br/>"
   myWriter.WriteLine("Hello, World!")
   myWriter.WriteLine("Hello, World, once again!")
End Sub

Notes

The Output property provides an alternative to the Response.Write method when outputting text to the output stream. You could also pass the TextWriter instance retrieved from the Output property to a method of a custom component to allow that component to write text directly to the output stream for the current response.

Like the Response.Write method, the result of writing text to the output stream by using the TextWriter returned from the Output property depends on the location of the code that writes the text. For example, in the code above, the text "Hello, World!" will appear before any static HTML in the page output. This is because the output of the TextWriter and the Response.Write method in this case is processed before the controls on the page are rendered. To make the output of the TextWriter instance or Response.Write appear inline, you could put the code above in a <% %> render block where you want the output to appear. A better approach for locating output in ASP.NET precisely is to add an ASP.NET Literal Server Control at the point in the file where you wish the output to appear and pass the desired output text to the Text property of the Literal control.

To use the TextWriter class without explicitly adding the System.IO namespace to the variable declaration, you can add the @ Import directive directly below the @ Page directive with the namespace attribute set to System.IO, as shown here:

<% @ Import Namespace="System.IO" %>
OutputStream

Stream = Response.OutputStream

Returns a write-only Stream object that can be used to write binary content directly to the output stream of the current request.

Parameter

Stream

An Object variable of type Stream. The Stream class includes the following members:

Member

Description

BeginWrite method

Begins an asynchronous write operation.

Close method

Closes the stream and releases its resources.

EndWrite method

Ends an asynchronous write operation.

Write method

Writes data to the stream.

WriteByte method

Writes a single byte to the stream and advances the position within the stream one byte.

Notes

The OutputStream property provides an alternative to the Response.BinaryWrite method when outputting binary content to the output stream is desired. You could also pass the Stream instance retrieved from the OutputStream property to a method of a custom component to allow that component to write binary content directly to the output stream for the current response.

Status

String = Response.Status
Response.Status = String

Returns or sets a String that contains the HTTP status line that will be sent to the client browser.

Parameter

String

A String variable to set or receive the status code of the current request. The default is "200 OK".

Notes

This property is provided for backward compatibility with classic ASP and has been deprecated in ASP.NET in favor of the StatusDescription property. Unlike the Status property, the StatusCode and StatusDescription properties allow you to control the numeric status code portion of the status line and the text description individually.

StatusCode

Integer = Response.StatusCode
Response.StatusCode = Integer

Returns or sets an integer that represents the HTTP status code that will be returned to the browser.

Parameter

Integer

An integer variable to set or receive the status code. The default is 200. The possible status codes fall into the following ranges:

1xx

The 100 range is for informational messages.

2xx

The 200 range is for success messages.

3xx

The 300 range is for redirection messages. The specific status code indicates whether a page has been moved temporarily or permanently.

4xx

The 400 range is for client error messages. The best-known message is the 404 Not Found message, which indicates that the client has asked for a resource that does not exist on the server. This range also includes status error messages related to client authentication.

5xx

The 500 range is for server error messages. For example, if more requests are received by IIS then can be processed or queued for later processing, clients will receive a 500-series status code with the "Server Too Busy" message.

Example

The example uses the StatusCode and StatusDescription properties to send an HTTP status message to the client. The Response.End method halts further processing and sends the currently buffered output to the client.

Sub Page_Load( )
   Response.StatusCode = 542
   Response.StatusDescription = "Server Error - The code is the answer."
   Response.End( )
End Sub

Notes

As with other properties that set HTTP response headers, this property cannot be set once HTTP body output is sent to the client using Response.Write or similar methods when buffering has been turned off.

StatusDescription

String = Response.StatusDescription
Response.StatusDescription = String

Returns or sets a string containing the text HTTP status message that will be sent to the browser along with the status code contained in the StatusCode property.

Parameter

String

A string variable to set or receive the additional path information. The default is OK.

Example

See the example for the StatusCode property.

Notes

As with other properties that set HTTP response headers, this property cannot be set once HTTP body output has been sent to the client (using Response.Write or similar methods) when buffering has been turned off.

SuppressContent

Boolean = Response.SuppressContent
Response.SuppressContent = Boolean

Returns or sets a Boolean indicating whether HTTP output should be sent to the client.

Parameter

Boolean

A Boolean variable to receive or set the value of the property. The default is False; content is sent to the client.

Example

The following example writes the text "Hello, World!" to the output (which is buffered by default) and sets SuppressContent to True so that no output is sent to the client.

Sub Page_Load( )
   Response.Write("Hello, World!")
   Response.SuppressContent = True
   If Response.SuppressContent Then Response.Close( )
End Sub

Notes

Since SuppressContent prevents any output from being returned to the client (including any error messages), the Response.Close method (which closes the network connection to the client) must be called to prevent the client browser from hanging indefinitely.

    [ Team LiB ] Previous Section Next Section