Buffer | |
Boolean = Response.Buffer |
|
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. |
|
Parameters
|
|
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 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 |
|
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. |
|
Parameters
|
|
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 ten 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:
|
|||||||||||||||
Parameters
|
|||||||||||||||
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. |
|
Parameters
|
|
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 |
|
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. |
|
Parameters
|
|
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 |
|
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. |
|
Parameters
|
|
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 |
|
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. |
|
Parameters
|
|
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 |
|
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. |
|
Parameters
|
|
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 |
|
Returns or sets a DateTime value representing the date and time at which a cached response should expire. |
|
Parameters
|
|
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. |
|
Parameters
|
|
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. |
|||||||||||||
Parameters
The TextWriter class includes the following members:
|
|||||||||||||
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. |
|||||||||||
Parameters
The Stream class includes the following members:
|
|||||||||||
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 |
|
Returns or sets a String that contains the HTTP status line that will be sent to the client browser. |
|
Parameters
|
|
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 |
|
Returns or sets an Integer that represents the HTTP status code that will be returned to the browser. |
|
Parameters
|
|
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 |
|
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. |
|
Parameters
|
|
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 |
|
Returns or sets a Boolean indicating whether HTTP output should be sent to the client. |
|
Parameters
|
|
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 If 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. |
Cookies | |
HttpCookieCollection = Response.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). The Cookies collection of the Response class supports the following set of properties:
|
|
In addition, the HttpCookieCollection class exposes the following methods:
|
|
As in classic ASP, the Cookies collection is still implemented as a collection (in fact, the HttpCookieCollection class 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 set individual values by their key with the following syntax: HttpCookie.Values(" keyname ") = " value " |
|
Parameters
|
|
Example | |
The example creates a login cookie, sets the expiration of the cookie for 30 minutes from the current time, and adds the cookie to the Cookies collection. Sub Page_Load( ) Dim myCookie As New HttpCookie("LoggedIn") myCookie.Value = "True" myCookie.Expires = DateTime.Now.AddMinutes(30) Response.Cookies.Add(myCookie) End Sub |
|
Notes | |
Unlike classic ASP, the collections in ASP.NET are zero-based, so the first element in any collection or array will be 0, not 1. This is especially important to remember when retrieving values by their index. |
AddCacheItemDependencies | |
Response.AddCacheItemDependencies(ByVal cacheKeys As ArrayList) |
|
Adds a list of cache keys contained in an ArrayList to the list of Cache item keys upon which the output cache of the current response depends. If one of the cache items identified by the keys is modified, the output cache of the current response will be invalidated and a fresh response will be generated. |
|
Parameters
|
|
Example | |
The example shows how you can use the AddCacheItemDependencies method to set a number of cache keys as dependencies for the output cache of the current response. If any of the cache items represented by these keys is modified, the output cache is invalidated and the page is refreshed by using Response.Redirect. <%@ Page Language="vb" %> <%@ OutputCache Duration="300" VaryByParam="None" %> <html> <head> <title>Adding cache dependencies in ASP.NET</title> <script runat="server"> Sub Page_Load( ) Dim myArrayList As New ArrayList myArrayList.Add("Key1") myArrayList.Add("Key2") Response.AddCacheItemDependencies(myArrayList) Message.Text = DateTime.Now.ToString( ) End Sub Sub Button1_Click(sender As Object, e As EventArgs) Cache("Key1") = "foo" & DateTime.Now.ToString() Response.Redirect("AddCacheItemDependencies.aspx") End Sub Sub Button2_Click(sender As Object, e As EventArgs) Cache("Key2") = "bar" & DateTime.Now.ToString() Response.Redirect("AddCacheItemDependencies.aspx") End Sub </script> </head> <body> <form runat="server"> <asp:label id="Message" runat="server"/> <asp:button id="Button1" text="Change Key 1" onClick="Button1_Click" runat="server"/> <asp:button id="Button2" text="Change Key 2" onClick="Button2_Click" runat="server"/> </form> </body> </html> |
|
Notes | |
The AddCacheItemDependencies method is useful when you want to output cache a page, but the page depends on the value of several items stored in the ASP.NET cache. Rather than caching the page with a very short duration to avoid stale data, you can use AddCacheItemDependencies to automatically invalidate the output cache when the dependencies change. |
AddCacheItemDependency | |
Response.AddCacheItemDependency(ByVal cacheKey As String) |
|
Adds a cache item key to the list of cache keys upon which the output cache of the current response depends. If the cache item identified by the key is modified, the output cache of the current response will be invalidated and a fresh response will be generated. |
|
Parameters
|
|
Example | |
The example shows how you can use the AddCacheItemDependency method to set a cache key as a dependency for the output cache of the current response. If the cache item represented by this key is modified, the output cache is invalidated and the page is refreshed by using Response.Redirect. <%@ Page Language="vb" %> <%@ OutputCache Duration="300" VaryByParam="None" %> <html> <head> <title>Adding a cache dependency in ASP.NET</title> <script runat="server"> Sub Page_Load( ) Response.AddCacheItemDependency("Key1") Message.Text = DateTime.Now.ToString( ) End Sub Sub Button1_Click(sender As Object, e As EventArgs) Cache("Key1") = "foo" & DateTime.Now.ToString( ) Response.Redirect("AddCacheItemDependency.aspx") End Sub </script> </head> <body> <form runat="server"> <asp:label id="Message" runat="server"/> <asp:button id="Button1" text="Change Key 1" onClick="Button1_Click" runat="server"/> </form> </body> </html> |
|
Notes | |
The AddCacheItemDependency method provides the same functionality as the AddCacheItemDependencies method, but for a single cache item rather than multiple items. |
AddFileDependencies | |
Response.AddFileDependencies(ByVal filenames As ArrayList) |
|
Adds a list of files contained in an ArrayList to the list of files upon which the output cache of the current request depends. If any of these files is modified, the output cache is invalidated. |
|
Parameters
|
|
Example | |
The example shows how you can use the AddFileDependencies method to set a number of files as dependencies for the output cache of the current response. If any of these files is modified, the output cache is invalidated. <%@ Page Language="vb" %> <%@ OutputCache Duration="300" VaryByParam="None" %> <html> <head> <title>Adding file dependencies in ASP.NET</title> <script runat="server"> Sub Page_Load( ) Dim myArrayList As New ArrayList myArrayList.Add(Server.MapPath("dep.txt")) myArrayList.Add(Server.MapPath("dep1.txt")) Response.AddFileDependencies(myArrayList) Message.Text = DateTime.Now.ToString( ) End Sub </script> </head> <body> <asp:label id="Message " runat="server"/> </body> </html> |
|
Notes | |
The AddFileDependencies method is useful when you want to output cache a page, but the page depends on the value of several files on the web server (which can be accessed by a file path from the web server). Rather than caching the page with a very short duration to avoid stale data, you can use AddFileDependencies to automatically invalidate the output cache when the dependencies change. |
AddFileDependency | |
Response.AddFileDependency(ByVal filename As String) |
|
Adds a file to the list of files upon which the output cache of the current request depends. If the named by the filename argument is modified, the output cache is invalidated. |
|
Parameters
|
|
Example | |
The example below shows how you can use the AddFileDependency method to set a file as a dependency for the output cache of the current response. If the file is modified, the output cache is invalidated. <%@ Page Language="vb" %> <%@ OutputCache Duration="300" VaryByParam="None" %> <html> <head> <title>Adding a file dependency in ASP.NET</title> <script runat="server"> Sub Page_Load( ) Response.AddFileDependency(Server.MapPath("dep.txt")) Message.Text = DateTime.Now.ToString( ) End Sub </script> </head> <body> <asp:label id="Message" runat="server"/> </body> </html> |
|
The dep.txt file named in the code above should reside in the same directory as the page. The contents of the page can be whatever you choose. If the file content is changed, the cache will be invalidated. |
|
Notes | |
The AddFileDependency method provides the same functionality as the AddFileDependencies method, but for a single file rather than multiple files. |
AddHeader | |
Response.AddHeader(ByVal name As String, ByVal value As String) |
|
Adds an HTTP header with the specified name and value to the output stream. |
|
Parameters
|
|
Notes | |
The AddHeader property provides for backward compatibility with classic ASP. This property has been deprecated in favor of the new AppendHeader method. |
AppendHeader | |
Response.AppendHeader(ByVal name As String, ByVal value As String) |
|
Adds an HTTP header with the specified name and value to the output stream. This method can be used to add custom HTTP headers or to modify the value of standard HTTP headers. |
|
Parameters
|
|
Example | |
The example sets the HTTP Content-Type header to "text/xml" and then displays the new value by setting the Text property of the Message Label control to the value of the ContentType property. This causes the page output to be treated as XML. Sub Page_Load( ) Response.AppendHeader("Content-Type", "text/xml") Message.Text = Response.ContentType End Sub |
|
Notes | |
When using this method with HTTP headers related to caching policy, if more restrictive settings are applied through the use of the ASP.NET cache APIs, the more restrictive settings will take priority over the settings applied using AppendHeader. |
AppendToLog | |
Response.AppendToLog(ByVal param As String) |
|
Appends the text specified by the param argument to the IIS log file for the current IIS application. |
|
Parameters
|
|
Example | |
The following example writes a message to the IIS log for the application the page is a part of, and then writes a message to the ASP.NET Message label control indicating that the message was written: Sub Page_Load( ) Response.AppendToLog("Hello from Page_Load!") Message.Text = "Message written to IIS Log!" End Sub |
|
The IIS log entry generated by the example above looks similar to the following: 2001-10-14 00:13:14 127.0.0.1 - 127.0.0.1 80 GET /ASPdotNET_iaN/Chapter_17/AppendToLog.aspx Hello+from+Page_Load! 200 BrowserString |
|
Notes | |
Unlike the AppendToLog method in classic ASP, which had a limit of 80 characters per call, you can write as much text as you wish to the log by using AppendToLog in ASP.NET. The IIS Log files are located by default in %windir%\System32\LogFiles\W3SVCx\exdate.log, where %windir% is the name of the Windows directory, x is the number of the Web site for the log (this is the IIS Metabase name for the desired application), and date is the creation date of the log file. |
ApplyAppPathModifier | |
String = Response.ApplyAppPathModifier(ByVal virtualPath_ As String) |
|
Given a virtual path to a resource, returns a string containing a new virtual path containing the SessionID. This new virtual path can be used to create absolute URLs for use in applications that use cookieless Sessions. |
|
Parameters
|
|
Example | |
The following example retrieves a virtual path including the SessionID and displays the path by using the Text property of the Message label control: Sub Page_Load( ) Dim NewPath As String NewPath = Response.ApplyAppPathModifier(Request.Path) Message.Text = "Modified virtual path = " & NewPath End Sub |
|
The web.config file to set the Session state handler to use cookieless Sessions is shown below: <configuration> <system.web> <sessionState mode="InProc" cookieless="true"/> </system.web> </configuration> |
|
Notes | |
This method is very useful when making use of the cookieless Session state functionality introduced by ASP.NET. If the cookieless attribute of the sessionState config section in web.config is not set to True, this method will simply return the virtual path passed in without modification. |
BinaryWrite | |
Response.BinaryWrite(ByVal buffer( ) As Byte) |
|
Allows writing of binary content to the output stream. No modification of the output is performed before sending the binary content to the client. |
|
Parameters
|
|
Example | |
Here is an example of BinaryWrite: Sub Page_Load( ) Dim ImageStream As New FileStream(MapPath("aspnetian.jpg"),_ FileMode.Open, FileAccess.Read) Dim ImageBytes(ImageStream.Length) As Byte ImageStream.Read(ImageBytes, 0, ImageStream.Length) ImageStream.Close() Response.ContentType = "image/bmp" Response.BinaryWrite(ImageBytes) Response.End( ) End Sub |
|
Notes | |
This method is especially useful for writing binary content retrieved from a database to the browser. When writing image or other nontext data to the browser, you should set the Response.ContentType property to the appropriate MIME type for the image type being sent (such as "image/jpg"). |
Clear | |
Response.Clear( ) |
|
Clears the content of the current output stream. |
|
Parameters | |
None |
|
Notes | |
The Clear method clears all currently buffered output, but does not clear the HTTP response headers. If buffering of output is disabled by setting the BufferOutput property to False, this method will not have any effect, since it only clears buffered content. This behavior is different from classic ASP, in which calling Clear when buffering is disabled results in an error. |
ClearContent | |
Response.ClearContent( ) |
|
Clears the content of the current output stream. |
|
Parameters | |
None |
|
Example | |
The example writes a text message using Response.Write and then clears the buffered output by calling Response.Clear. If buffering is on, the text message will never be sent to the browser. Sub Page_Load( ) Response.Write("This content will not be seen.") Response.Clear( ) Message.Text = "Content written with <i>Response.Write</i> was cleared." End Sub |
|
Notes | |
The ClearContent method clears all currently buffered output, but does not clear the HTTP response headers. HTTP headers can be cleared by calling the ClearHeaders method. If buffering of output has been disabled by setting the BufferOutput property to False, the ClearContent method will not have any effect, since it only clears buffered content. |
ClearHeaders | |
Response.ClearHeaders( ) |
|
Clears the HTTP headers from the current output stream. |
|
Parameters | |
None |
|
Example | |
The example sets the HTTP Content-Type header to "text/xml", clears the HTTP headers by calling the ClearHeaders method, and then writes the value of the Response.ContentType property to the Text property of the Message ASP.NET Label control. The displayed Content-Type is the default of "text/html". Sub Page_Load( ) Response.AppendHeader("Content-Type", "text/xml") Response.ClearHeaders( ) Message.Text = Response.ContentType End Sub |
|
Notes | |
The ClearHeaders method clears only the HTTP response headers, not the buffered content. |
Close | |
Response.Close( ) |
|
Closes the network socket for the current response. |
|
Parameters | |
None |
|
Example | |
See the example for the SuppressContent property. |
|
Notes | |
The Close method can be used to immediately close the network socket for the current response. This closure will typically result in a browser error (such as "Cannot find server") being displayed to the client. |
End | |
Response.End( ) |
|
Stops processing the current request and sends all buffered content to the client immediately. |
|
Parameters | |
None |
|
Example | |
The example below writes the text "Hello, World!" to the browser, calls Response.End, and then attempts to set the Text property of the Message ASP.NET Label control to "Hello, World!" However, that code will not be executed, as the End method immediately halts execution of page processing. Sub Page_Load( ) Response.Write("Hello, World!") Response.End() Message.Text = "Hello, World!" End Sub |
|
In fact, the code above will result in only the "Hello, World!" text being output to the browser, as even the rendering of the static HTML and controls in the page will not occur. |
|
Notes | |
When the End method is called, in addition to sending buffered output to the client and terminating processing, the Application_EndRequest event is fired. |
Flush | |
Response.Flush( ) |
|
Immediately sends all buffered output to the client. |
|
Parameters | |
None |
|
Example | |
See the example for the BufferOutput property. If you comment out the lines that set BufferOutput to False and then uncomment the line that calls Response.Flush, you will see that the Flush method allows you to explicitly send buffered content to the browser. |
|
Notes | |
Since buffering is on by default in ASP.NET, the Flush method becomes especially useful. Rather than turning off buffering, which results in any content sent from a Response.Write call being sent immediately to the browser, you can use Response.Flush to send content in discrete chunks or to ensure that an entire operation completes before sending the currently buffered content. |
|
You can also combine calls to Response.Flush with calls to Response.Clear to allow you to perform preverification on content before it is sent to the browser. If a given set of calculations or output encounters an error, you can call Response.Clear to clear the problematic output and then replace it with an error message or with other replacement content. If there are no problems with the output, you can call Response.Flush to send the buffered output to the browser and then continue processing. |
Pics | |
Response.Pics(ByVal value As String) |
|
Adds a PICS-Label header to the output stream for the current response. The Platform for Internet Content Selection (PICS) is used to rate Internet content based on violence, sexual content, language, and nudity. |
|
Parameters
|
|
Example | |
The following example sets a PICS header that specifies RSAC as the rating organization, sets the rating effective period from 8/1/2001 to 2/28/2002, and sets the ratings as follows:
Sub Page_Load( ) Dim PICSLabel As String PICSLabel &= "(PICS-1.1 <http://www.rsac.org/ratingsv01.html> " PICSLabel &= "labels on " & Chr(34) PICSLabel &= "2001.08.01T06:00-0000" & Chr(34) PICSLabel &= " until " & Chr(34) PICSLabel &= "2002.02.28T23:59-0000" & Chr(34) PICSLabel &= " ratings (V 1 S 2 L 3 N 4))" Response.PICS(PICSLabel) Message.Text = PICSLabel End Sub |
|
Notes | |
The PICS-Label header is used for rating the content of a site. Users can configure their browsers to disallow viewing of sites that send PICS-Label headers, and whose ratings state that the site contains a higher level of content in one of the rated categories than the browser is configured to allow. Additional information on the PICS standard for content ratings is available at the World Wide Web Consortium web site at http://www.w3c.org. |
Redirect | |
Response.Redirect(ByVal url As String) Response.Redirect(ByVal url As String, ByVal endResponse As Boolean) |
|
Redirects the currently executing page to another page specified by the URL argument, optionally terminating the processing of the current page. |
|
Parameters
|
|
Example | |
The example redirects the current request to BufferOutput.aspx and directs ASP.NET to discontinue processing of the current page: Sub Page_Load( ) Response.Redirect("BufferOutput.aspx", True) End Sub |
|
Notes | |
Unless additional processing needs to be done in the page from which you call Response.Redirect, you should always pass True as the second argument to Response.Redirect to prevent server resources from being wasted by continuing to process the current page. This feature is new for ASP.NET. When calling Response.Redirect with only the url argument, processing of the current page is discontinued automatically. |
|
Note that when redirecting to a page such as BufferOutput.aspx in which buffering is turned off, or to a page that calls Response.Flush, the redirect will not complete until the target page has completed processing. This means that all content on the target page will be seen at once, rather than as it is rendered or flushed from the buffer. |
Write | |
Response.Write(ByVal ch As Char) Response.Write(ByVal obj As Object) Response.Write(ByVal s As String) Response.Write(ByVal buffer( ) As Char, ByVal index As Integer, ByVal count As Integer) |
|
Allows writing of arbitrary content to the output stream. Content may be character data, an Object (using the object's ToString( ) method), or String data. |
|
Parameters
|
|
Example | |
The example creates an array of Chars, sets the values of the Chars, and then loops through the array and displays its contents by calling Response.Write: Sub Page_Load( ) Dim MyChars(2) As Char Dim MyChar As Char MyChars(0) = CChar("A") MyChars(1) = CChar("B") MyChars(2) = CChar("C") For Each MyChar in MyChars Response.Write(MyChar) Next End Sub |
|
Notes | |
As shown above, the Write method in ASP.NET gains a number of new overloaded implementations. The above code could also be written by using another overloaded implementation that accepts an array of Chars, a starting index, and the count of Chars to write, as follows: Response.Write(MyChars, 0, 3) |
|
The implementation of the Write method that takes an Object as an argument takes advantage of the built-in ToString method of the object class to display the string representation of the object. ToString is inherited by every .NET class and, by default, returns the namespace and class name of the object's class. Classes that wish to send other information about themselves can override the inherited implementation of ToString to send this information. |
WriteFile | |
Response.WriteFile(ByVal fileName As String) Response.WriteFile(ByVal fileName As String, ByVal includeHeaders As Boolean) Response.WriteFile(ByVal fileHandle As IntPtr, ByVal offset As Long, ByVal size As Long) Response.WriteFile(ByVal fileName As String, ByVal offset As Long, ByVal size As Long) |
|
Writes a file specified in one of the overloaded arguments to the output stream. |
|
Parameters
|
|
Example | |
The example writes the contents of the file dep.txt to the output stream of the current response. Sub Page_Load( ) Response.WriteFile("dep.txt") End Sub |
|
Notes | |
The WriteFile method can be used in a variety of ways to output text content directly from a file. Attempts to write other content types (such as image data) will fail. |