HttpResponse HttpResponse HttpResponse HttpResponse Class

Definition

Encapsulates HTTP-response information from an ASP.NET operation.

public ref class HttpResponse sealed
public sealed class HttpResponse
type HttpResponse = class
Public NotInheritable Class HttpResponse
Inheritance
HttpResponseHttpResponseHttpResponseHttpResponse

Examples

The following example draws three overlapping rectangles when the page is requested. The code begins by setting the ContentType property to image/jpeg, so that the entire page will be rendered as a JPEG image. The code then calls the Clear method to ensure that no extraneous content is sent with this response. Next, the code sets the BufferOutput property to true so that the page is completely processed before it is sent to the requesting client. Two objects used to draw the rectangles are then created: a Bitmap and a Graphics object. The variables created in the page are used as coordinates to draw the rectangles and a string that appears inside the largest rectangle.

When the three rectangles and the string that appears inside them are drawn, the Bitmap is saved to the Stream object that is associated with the OutputStream property and its format is set to JPEG. The code calls the Dispose and Dispose methods to release the resources used by the two drawing objects. Lastly, the code calls the Flush method to send the buffered response to the requesting client.

Note

In code, the HttpResponse object is referred to by the keyword Response. For example, Response.Clear() refers to the HttpResponse.Clear method. The Page class has a property that is named Response that exposes the current instance of HttpResponse.

<%@ Page Language="C#" %>
<%@ import Namespace="System.Drawing" %>
<%@ import Namespace="System.Drawing.Imaging" %>
<%@ import Namespace="System.Drawing.Drawing2D" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    private void Page_Load(object sender, EventArgs e)
    {
// <snippet2>
        // Set the page's content type to JPEG files
        // and clears all content output from the buffer stream.
        Response.ContentType = "image/jpeg";
        Response.Clear();
    
        // Buffer response so that page is sent
        // after processing is complete.
        Response.BufferOutput = true;
// </snippet2>
    
        // Create a font style.
        Font rectangleFont = new Font(
            "Arial", 10, FontStyle.Bold);
    
        // Create integer variables.
        int height = 100;
        int width = 200;
    
        // Create a random number generator and create
        // variable values based on it.
        Random r = new Random();
        int x = r.Next(75);
        int a = r.Next(155);
        int x1 = r.Next(100);
    
        // Create a bitmap and use it to create a
        // Graphics object.
        Bitmap bmp = new Bitmap(
            width, height, PixelFormat.Format24bppRgb);
        Graphics g = Graphics.FromImage(bmp);
    
        g.SmoothingMode = SmoothingMode.AntiAlias;
        g.Clear(Color.LightGray);
    
        // Use the Graphics object to draw three rectangles.
        g.DrawRectangle(Pens.White, 1, 1, width-3, height-3);
        g.DrawRectangle(Pens.Aquamarine, 2, 2, width-3, height-3);
        g.DrawRectangle(Pens.Black, 0, 0, width, height);
    
        // Use the Graphics object to write a string
        // on the rectangles.
        g.DrawString(
            "ASP.NET Samples", rectangleFont,
            SystemBrushes.WindowText, new PointF(10, 40));
    
        // Apply color to two of the rectangles.
        g.FillRectangle(
            new SolidBrush(
                Color.FromArgb(a, 255, 128, 255)),
            x, 20, 100, 50);
    
        g.FillRectangle(
            new LinearGradientBrush(
                new Point(x, 10),
                new Point(x1 + 75, 50 + 30),
                Color.FromArgb(128, 0, 0, 128),
                Color.FromArgb(255, 255, 255, 240)),
            x1, 50, 75, 30);

// <snippet3>    
        // Save the bitmap to the response stream and
        // convert it to JPEG format.
        bmp.Save(Response.OutputStream, ImageFormat.Jpeg);
    
        // Release memory used by the Graphics object
        // and the bitmap.
        g.Dispose();
        bmp.Dispose();
    
        // Send the output to the client.
        Response.Flush();
// </snippet3>
    }

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ import Namespace="System.Drawing" %>
<%@ import Namespace="System.Drawing.Imaging" %>
<%@ import Namespace="System.Drawing.Drawing2D" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

   Private Sub Page_Load(sender As Object, e As EventArgs)
' <snippet2>
      ' Set the page's content type to JPEG files
      ' and clears all content output from the buffer stream.
      Response.ContentType = "image/jpeg"
      Response.Clear()
      
      ' Buffer response so that page is sent
      ' after processing is complete.
      Response.BufferOutput = True
' </snippet2>
      
      ' Create a font style.
      Dim rectangleFont As New Font( _
          "Arial", 10, FontStyle.Bold)
      
      ' Create integer variables.
      Dim height As Integer = 100
      Dim width As Integer = 200
      
      ' Create a random number generator and create
      ' variable values based on it.
      Dim r As New Random()
      Dim x As Integer = r.Next(75)
      Dim a As Integer = r.Next(155)
      Dim x1 As Integer = r.Next(100)
      
      ' Create a bitmap and use it to create a
      ' Graphics object.
      Dim bmp As New Bitmap( _
          width, height, PixelFormat.Format24bppRgb)
      Dim g As Graphics = Graphics.FromImage(bmp)
      
      g.SmoothingMode = SmoothingMode.AntiAlias
      g.Clear(Color.LightGray)
      
      ' Use the Graphics object to draw three rectangles.
      g.DrawRectangle(Pens.White, 1, 1, width - 3, height - 3)
      g.DrawRectangle(Pens.Aquamarine, 2, 2, width - 3, height - 3)
      g.DrawRectangle(Pens.Black, 0, 0, width, height)
      
      ' Use the Graphics object to write a string
      ' on the rectangles.
      g.DrawString("ASP.NET Samples", rectangleFont, SystemBrushes.WindowText, New PointF(10, 40))
      
      ' Apply color to two of the rectangles.
      g.FillRectangle( _
          New SolidBrush( _
              Color.FromArgb(a, 255, 128, 255)), _
          x, 20, 100, 50)
      
      g.FillRectangle( _
          New LinearGradientBrush( _
              New Point(x, 10), _
              New Point(x1 + 75, 50 + 30), _
              Color.FromArgb(128, 0, 0, 128), _
              Color.FromArgb(255, 255, 255, 240)), _
          x1, 50, 75, 30)

' <snippet3>      
      ' Save the bitmap to the response stream and
      ' convert it to JPEG format.
      bmp.Save(Response.OutputStream, ImageFormat.Jpeg)
      
      ' Release memory used by the Graphics object
      ' and the bitmap.
      g.Dispose()
      bmp.Dispose()
      
      ' Send the output to the client.
      Response.Flush()
' </snippet3>
   End Sub 'Page_Load

</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>ASP.NET Example</title>
</head>
<body>
    <form id="form1" runat="server">
    </form>
</body>
</html>

Remarks

The methods and properties of the HttpResponse class are exposed through the Response property of the HttpApplication, HttpContext, Page, and UserControl classes.

The following methods of the HttpResponse class are supported only in post back scenarios and not in asynchronous post back scenarios:

Partial-page updates are enabled when you use UpdatePanel controls to update selected regions of a page instead of updating the whole page with a post back. For more information, see UpdatePanel Control Overview and Partial-Page Rendering Overview.

Constructors

HttpResponse(TextWriter) HttpResponse(TextWriter) HttpResponse(TextWriter) HttpResponse(TextWriter)

Initializes a new instance of the HttpResponse class.

Properties

Buffer Buffer Buffer Buffer

Gets or sets a value indicating whether to buffer output and send it after the complete response is finished processing.

BufferOutput BufferOutput BufferOutput BufferOutput

Gets or sets a value indicating whether to buffer output and send it after the complete page is finished processing.

Cache Cache Cache Cache

Gets the caching policy (such as expiration time, privacy settings, and vary clauses) of a Web page.

CacheControl CacheControl CacheControl CacheControl

Gets or sets the Cache-Control HTTP header that matches one of the HttpCacheability enumeration values.

Charset Charset Charset Charset

Gets or sets the HTTP character set of the output stream.

ClientDisconnectedToken ClientDisconnectedToken ClientDisconnectedToken ClientDisconnectedToken

Gets a CancellationToken object that is tripped when the client disconnects.

ContentEncoding ContentEncoding ContentEncoding ContentEncoding

Gets or sets the HTTP character set of the output stream.

ContentType ContentType ContentType ContentType

Gets or sets the HTTP MIME type of the output stream.

Cookies Cookies Cookies Cookies

Gets the response cookie collection.

Expires Expires Expires Expires

Gets or sets the number of minutes before a page cached on a browser expires. If the user returns to the same page before it expires, the cached version is displayed. Expires is provided for compatibility with earlier versions of ASP.

ExpiresAbsolute ExpiresAbsolute ExpiresAbsolute ExpiresAbsolute

Gets or sets the absolute date and time at which to remove cached information from the cache. ExpiresAbsolute is provided for compatibility with earlier versions of ASP.

Filter Filter Filter Filter

Gets or sets a wrapping filter object that is used to modify the HTTP entity body before transmission.

HeaderEncoding HeaderEncoding HeaderEncoding HeaderEncoding

Gets or sets an Encoding object that represents the encoding for the current header output stream.

Headers Headers Headers Headers

Gets the collection of response headers.

HeadersWritten HeadersWritten HeadersWritten HeadersWritten

[Supported in the .NET Framework 4.5.2 and later versions]

Gets a value indicating whether the response headers have been written.

IsClientConnected IsClientConnected IsClientConnected IsClientConnected

Gets a value indicating whether the client is still connected to the server.

IsRequestBeingRedirected IsRequestBeingRedirected IsRequestBeingRedirected IsRequestBeingRedirected

Gets a Boolean value indicating whether the client is being transferred to a new location.

Output Output Output Output

Enables output of text to the outgoing HTTP response stream.

OutputStream OutputStream OutputStream OutputStream

Enables binary output to the outgoing HTTP content body.

RedirectLocation RedirectLocation RedirectLocation RedirectLocation

Gets or sets the value of the HTTP Location header.

Status Status Status Status

Sets the Status line that is returned to the client.

StatusCode StatusCode StatusCode StatusCode

Gets or sets the HTTP status code of the output returned to the client.

StatusDescription StatusDescription StatusDescription StatusDescription

Gets or sets the HTTP status string of the output returned to the client.

SubStatusCode SubStatusCode SubStatusCode SubStatusCode

Gets or sets a value qualifying the status code of the response.

SupportsAsyncFlush SupportsAsyncFlush SupportsAsyncFlush SupportsAsyncFlush

Gets a value that indicates whether the connection supports asynchronous flush operations.

SuppressContent SuppressContent SuppressContent SuppressContent

Gets or sets a value indicating whether to send HTTP content to the client.

SuppressDefaultCacheControlHeader SuppressDefaultCacheControlHeader SuppressDefaultCacheControlHeader SuppressDefaultCacheControlHeader

[Supported in the .NET Framework 4.5.2 and later versions]

Gets or sets a value indicating whether to suppress the default Cache Control: private header for the current HTTP response.

SuppressFormsAuthenticationRedirect SuppressFormsAuthenticationRedirect SuppressFormsAuthenticationRedirect SuppressFormsAuthenticationRedirect

Gets or sets a value that specifies whether forms authentication redirection to the login page should be suppressed.

TrySkipIisCustomErrors TrySkipIisCustomErrors TrySkipIisCustomErrors TrySkipIisCustomErrors

Gets or sets a value that specifies whether IIS 7.0 custom errors are disabled.

Methods

AddCacheDependency(CacheDependency[]) AddCacheDependency(CacheDependency[]) AddCacheDependency(CacheDependency[]) AddCacheDependency(CacheDependency[])

Associates a set of cache dependencies with the response to facilitate invalidation of the response if it is stored in the output cache and the specified dependencies change.

AddCacheItemDependencies(ArrayList) AddCacheItemDependencies(ArrayList) AddCacheItemDependencies(ArrayList) AddCacheItemDependencies(ArrayList)

Makes the validity of a cached response dependent on other items in the cache.

AddCacheItemDependencies(String[]) AddCacheItemDependencies(String[]) AddCacheItemDependencies(String[]) AddCacheItemDependencies(String[])

Makes the validity of a cached item dependent on another item in the cache.

AddCacheItemDependency(String) AddCacheItemDependency(String) AddCacheItemDependency(String) AddCacheItemDependency(String)

Makes the validity of a cached response dependent on another item in the cache.

AddFileDependencies(ArrayList) AddFileDependencies(ArrayList) AddFileDependencies(ArrayList) AddFileDependencies(ArrayList)

Adds a group of file names to the collection of file names on which the current response is dependent.

AddFileDependencies(String[]) AddFileDependencies(String[]) AddFileDependencies(String[]) AddFileDependencies(String[])

Adds an array of file names to the collection of file names on which the current response is dependent.

AddFileDependency(String) AddFileDependency(String) AddFileDependency(String) AddFileDependency(String)

Adds a single file name to the collection of file names on which the current response is dependent.

AddHeader(String, String) AddHeader(String, String) AddHeader(String, String) AddHeader(String, String)

Adds an HTTP header to the output stream. AddHeader(String, String) is provided for compatibility with earlier versions of ASP.

AddOnSendingHeaders(Action<HttpContext>) AddOnSendingHeaders(Action<HttpContext>) AddOnSendingHeaders(Action<HttpContext>) AddOnSendingHeaders(Action<HttpContext>)

[Supported in the .NET Framework 4.5.2 and later versions]

Registers a callback that the ASP.NET runtime will invoke immediately before response headers are sent for this request.

AppendCookie(HttpCookie) AppendCookie(HttpCookie) AppendCookie(HttpCookie) AppendCookie(HttpCookie)

Adds an HTTP cookie to the intrinsic cookie collection.

AppendHeader(String, String) AppendHeader(String, String) AppendHeader(String, String) AppendHeader(String, String)

Adds an HTTP header to the output stream.

AppendToLog(String) AppendToLog(String) AppendToLog(String) AppendToLog(String)

Adds custom log information to the Internet Information Services (IIS) log file.

ApplyAppPathModifier(String) ApplyAppPathModifier(String) ApplyAppPathModifier(String) ApplyAppPathModifier(String)

Adds a session ID to the virtual path if the session is using Cookieless session state and returns the combined path. If Cookieless session state is not used, ApplyAppPathModifier(String) returns the original virtual path.

BeginFlush(AsyncCallback, Object) BeginFlush(AsyncCallback, Object) BeginFlush(AsyncCallback, Object) BeginFlush(AsyncCallback, Object)

Sends the currently buffered response to the client.

BinaryWrite(Byte[]) BinaryWrite(Byte[]) BinaryWrite(Byte[]) BinaryWrite(Byte[])

Writes a string of binary characters to the HTTP output stream.

Clear() Clear() Clear() Clear()

Clears all content output from the buffer stream.

ClearContent() ClearContent() ClearContent() ClearContent()

Clears all content output from the buffer stream.

ClearHeaders() ClearHeaders() ClearHeaders() ClearHeaders()

Clears all headers from the buffer stream.

Close() Close() Close() Close()

Closes the socket connection to a client.

DisableKernelCache() DisableKernelCache() DisableKernelCache() DisableKernelCache()

Disables kernel caching for the current response.

DisableUserCache() DisableUserCache() DisableUserCache() DisableUserCache()

Disables IIS user-mode caching for this response.

End() End() End() End()

Sends all currently buffered output to the client, stops execution of the page, and raises the EndRequest event.

EndFlush(IAsyncResult) EndFlush(IAsyncResult) EndFlush(IAsyncResult) EndFlush(IAsyncResult)

Completes an asynchronous flush operation.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Flush() Flush() Flush() Flush()

Sends all currently buffered output to the client.

FlushAsync() FlushAsync() FlushAsync() FlushAsync()

Asynchronously sends all currently buffered output to the client.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
Pics(String) Pics(String) Pics(String) Pics(String)

Appends a HTTP PICS-Label header to the output stream.

PushPromise(String) PushPromise(String) PushPromise(String) PushPromise(String)

This API is to support applications sending push promises to HTTP 2.0 clients. You can find more details regarding to Http2 server push at HTTP/2 Specification Section 8.2: Server Push.

PushPromise(String, String, NameValueCollection) PushPromise(String, String, NameValueCollection) PushPromise(String, String, NameValueCollection) PushPromise(String, String, NameValueCollection)

This API is to support applications sending push promises to HTTP 2.0 clients. You can find more details regarding to Http2 server push at HTTP/2 Specification Section 8.2: Server Push.

Redirect(String) Redirect(String) Redirect(String) Redirect(String)

Redirects a request to a new URL and specifies the new URL.

Redirect(String, Boolean) Redirect(String, Boolean) Redirect(String, Boolean) Redirect(String, Boolean)

Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate.

RedirectPermanent(String) RedirectPermanent(String) RedirectPermanent(String) RedirectPermanent(String)

Performs a permanent redirection from the requested URL to the specified URL.

RedirectPermanent(String, Boolean) RedirectPermanent(String, Boolean) RedirectPermanent(String, Boolean) RedirectPermanent(String, Boolean)

Performs a permanent redirection from the requested URL to the specified URL, and provides the option to complete the response.

RedirectToRoute(Object) RedirectToRoute(Object) RedirectToRoute(Object) RedirectToRoute(Object)

Redirects a request to a new URL by using route parameter values.

RedirectToRoute(RouteValueDictionary) RedirectToRoute(RouteValueDictionary) RedirectToRoute(RouteValueDictionary) RedirectToRoute(RouteValueDictionary)

Redirects a request to a new URL by using route parameter values.

RedirectToRoute(String) RedirectToRoute(String) RedirectToRoute(String) RedirectToRoute(String)

Redirects a request to a new URL by using a route name.

RedirectToRoute(String, Object) RedirectToRoute(String, Object) RedirectToRoute(String, Object) RedirectToRoute(String, Object)

Redirects a request to a new URL by using route parameter values and a route name.

RedirectToRoute(String, RouteValueDictionary) RedirectToRoute(String, RouteValueDictionary) RedirectToRoute(String, RouteValueDictionary) RedirectToRoute(String, RouteValueDictionary)

Redirects a request to a new URL by using route parameter values and a route name.

RedirectToRoutePermanent(Object) RedirectToRoutePermanent(Object) RedirectToRoutePermanent(Object) RedirectToRoutePermanent(Object)

Performs a permanent redirection from a requested URL to a new URL by using route parameter values.

RedirectToRoutePermanent(RouteValueDictionary) RedirectToRoutePermanent(RouteValueDictionary) RedirectToRoutePermanent(RouteValueDictionary) RedirectToRoutePermanent(RouteValueDictionary)

Performs a permanent redirection from a requested URL to a new URL by using route parameter values.

RedirectToRoutePermanent(String) RedirectToRoutePermanent(String) RedirectToRoutePermanent(String) RedirectToRoutePermanent(String)

Performs a permanent redirection from a requested URL to a new URL by using a route name.

RedirectToRoutePermanent(String, Object) RedirectToRoutePermanent(String, Object) RedirectToRoutePermanent(String, Object) RedirectToRoutePermanent(String, Object)

Performs a permanent redirection from a requested URL to a new URL by using the route parameter values and the name of the route that correspond to the new URL.

RedirectToRoutePermanent(String, RouteValueDictionary) RedirectToRoutePermanent(String, RouteValueDictionary) RedirectToRoutePermanent(String, RouteValueDictionary) RedirectToRoutePermanent(String, RouteValueDictionary)

Performs a permanent redirection from a requested URL to a new URL by using route parameter values and a route name.

RemoveOutputCacheItem(String) RemoveOutputCacheItem(String) RemoveOutputCacheItem(String) RemoveOutputCacheItem(String)

Removes from the cache all cached items that are associated with the default output-cache provider. This method is static.

RemoveOutputCacheItem(String, String) RemoveOutputCacheItem(String, String) RemoveOutputCacheItem(String, String) RemoveOutputCacheItem(String, String)

Uses the specified output-cache provider to remove all output-cache items that are associated with the specified path.

SetCookie(HttpCookie) SetCookie(HttpCookie) SetCookie(HttpCookie) SetCookie(HttpCookie)

Because the HttpResponse.SetCookie method is intended for internal use only, you should not call it in your code. Instead, you can call the HttpResponse.Cookies.Set method, as the following example shows.
Updates an existing cookie in the cookie collection.

ToString() ToString() ToString() ToString()

Returns a string that represents the current object.

(Inherited from Object)
TransmitFile(String) TransmitFile(String) TransmitFile(String) TransmitFile(String)

Writes the specified file directly to an HTTP response output stream, without buffering it in memory.

TransmitFile(String, Int64, Int64) TransmitFile(String, Int64, Int64) TransmitFile(String, Int64, Int64) TransmitFile(String, Int64, Int64)

Writes the specified part of a file directly to an HTTP response output stream without buffering it in memory.

Write(Char) Write(Char) Write(Char) Write(Char)

Writes a character to an HTTP response output stream.

Write(Char[], Int32, Int32) Write(Char[], Int32, Int32) Write(Char[], Int32, Int32) Write(Char[], Int32, Int32)

Writes an array of characters to an HTTP response output stream.

Write(Object) Write(Object) Write(Object) Write(Object)

Writes an Object to an HTTP response stream.

Write(String) Write(String) Write(String) Write(String)

Writes a string to an HTTP response output stream.

WriteFile(IntPtr, Int64, Int64) WriteFile(IntPtr, Int64, Int64) WriteFile(IntPtr, Int64, Int64) WriteFile(IntPtr, Int64, Int64)

Writes the specified file directly to an HTTP response output stream.

WriteFile(String) WriteFile(String) WriteFile(String) WriteFile(String)

Writes the contents of the specified file directly to an HTTP response output stream as a file block.

WriteFile(String, Boolean) WriteFile(String, Boolean) WriteFile(String, Boolean) WriteFile(String, Boolean)

Writes the contents of the specified file directly to an HTTP response output stream as a memory block.

WriteFile(String, Int64, Int64) WriteFile(String, Int64, Int64) WriteFile(String, Int64, Int64) WriteFile(String, Int64, Int64)

Writes the specified file directly to an HTTP response output stream.

WriteSubstitution(HttpResponseSubstitutionCallback) WriteSubstitution(HttpResponseSubstitutionCallback) WriteSubstitution(HttpResponseSubstitutionCallback) WriteSubstitution(HttpResponseSubstitutionCallback)

Allows insertion of response substitution blocks into the response, which allows dynamic generation of specified response regions for output cached responses.

Applies to