HttpResponse 类

定义

封装来自 ASP.NET 操作的 HTTP 响应信息。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
继承
HttpResponse

示例

下面的示例在请求页时绘制三个重叠矩形。The following example draws three overlapping rectangles when the page is requested. 代码首先将ContentType属性设置为 image/jpeg,使整个页面呈现为 jpeg 图像。The code begins by setting the ContentType property to image/jpeg, so that the entire page will be rendered as a JPEG image. 然后,该代码调用Clear方法,以确保不会随此响应发送无关的内容。The code then calls the Clear method to ensure that no extraneous content is sent with this response. 接下来,代码将BufferOutput属性设置为 true,以便在将页发送到请求客户端之前对其进行完全处理。Next, the code sets the BufferOutput property to true so that the page is completely processed before it is sent to the requesting client. 然后创建两个用于绘制矩形的对象:一个Bitmap和一个Graphics对象。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.

绘制三个矩形和其中显示的字符串时, Bitmap将保存到与OutputStream属性相关联的Stream对象,并将其格式设置为 "JPEG"。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. 此代码调用DisposeDispose方法以释放由两个图形对象使用的资源。The code calls the Dispose and Dispose methods to release the resources used by the two drawing objects. 最后,该代码调用Flush方法将缓冲响应发送到请求客户端。Lastly, the code calls the Flush method to send the buffered response to the requesting client.

备注

在代码中, HttpResponse由关键字Response引用对象。In code, the HttpResponse object is referred to by the keyword Response. 例如, Response.Clear()表示HttpResponse.Clear方法。For example, Response.Clear() refers to the HttpResponse.Clear method. 类具有一个名Response为的属性,该属性HttpResponse公开的当前实例。 PageThe 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>

注解

HttpResponse类的方法和属性Response通过HttpApplicationHttpContextPage和类的属性公开。UserControlThe methods and properties of the HttpResponse class are exposed through the Response property of the HttpApplication, HttpContext, Page, and UserControl classes.

仅在回发方案HttpResponse (而不是异步回发方案)中支持类的以下方法:The following methods of the HttpResponse class are supported only in post back scenarios and not in asynchronous post back scenarios:

当您使用UpdatePanel控件更新页面的选定区域,而不是使用回发更新整个页面时,会启用部分页面更新。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. 有关详细信息, 请参阅UpdatePanel 控件概述部分页呈现概述For more information, see UpdatePanel Control Overview and Partial-Page Rendering Overview.

构造函数

HttpResponse(TextWriter)

初始化 HttpResponse 类的新实例。Initializes a new instance of the HttpResponse class.

属性

Buffer

获取或设置一个值,该值指示是否缓冲输出并在处理完整个响应之后发送它。Gets or sets a value indicating whether to buffer output and send it after the complete response is finished processing.

BufferOutput

获取或设置一个值,该值指示是否缓冲输出并在处理完整个页之后发送它。Gets or sets a value indicating whether to buffer output and send it after the complete page is finished processing.

Cache

获取网页的缓存策略(例如:过期时间、保密性设置和变化条款)。Gets the caching policy (such as expiration time, privacy settings, and vary clauses) of a Web page.

CacheControl

获取或设置与 HttpCacheability 枚举值之一匹配的 Cache-Control HTTP 标头。Gets or sets the Cache-Control HTTP header that matches one of the HttpCacheability enumeration values.

Charset

获取或设置输出流的 HTTP 字符集。Gets or sets the HTTP character set of the output stream.

ClientDisconnectedToken

获取客户端断开连接时触发的 CancellationToken 对象。Gets a CancellationToken object that is tripped when the client disconnects.

ContentEncoding

获取或设置输出流的 HTTP 字符集。Gets or sets the HTTP character set of the output stream.

ContentType

获取或设置输出流的 HTTP MIME 类型。Gets or sets the HTTP MIME type of the output stream.

Cookies

获取响应 cookie 集合。Gets the response cookie collection.

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,以便兼容 ASP 的早期版本。Expires is provided for compatibility with earlier versions of ASP.

ExpiresAbsolute

获取或设置从缓存中移除缓存信息的绝对日期和时间。Gets or sets the absolute date and time at which to remove cached information from the cache. 提供 ExpiresAbsolute,以便兼容 ASP 的早期版本。ExpiresAbsolute is provided for compatibility with earlier versions of ASP.

Filter

获取或设置一个包装筛选器对象,该对象用于在传输之前修改 HTTP 实体主体。Gets or sets a wrapping filter object that is used to modify the HTTP entity body before transmission.

HeaderEncoding

获取或设置一个 Encoding 对象,该对象表示当前标头输出流的编码。Gets or sets an Encoding object that represents the encoding for the current header output stream.

Headers

获取响应标头的集合。Gets the collection of response headers.

HeadersWritten

获取指示是否已写入响应标头的值。Gets a value indicating whether the response headers have been written.

IsClientConnected

获取一个值,通过该值指示客户端是否仍连接在服务器上。Gets a value indicating whether the client is still connected to the server.

IsRequestBeingRedirected

获取一个布尔值,该值指示客户端是否正在被传输到新的位置。Gets a Boolean value indicating whether the client is being transferred to a new location.

Output

启用到输出 HTTP 响应流的文本输出。Enables output of text to the outgoing HTTP response stream.

OutputStream

启用到输出 HTTP 内容主体的二进制输出。Enables binary output to the outgoing HTTP content body.

RedirectLocation

获取或设置 HTTP Location 标头的值。Gets or sets the value of the HTTP Location header.

Status

设置返回到客户端的 Status 栏。Sets the Status line that is returned to the client.

StatusCode

获取或设置返回给客户端的输出的 HTTP 状态代码。Gets or sets the HTTP status code of the output returned to the client.

StatusDescription

获取或设置返回给客户端的输出的 HTTP 状态字符串。Gets or sets the HTTP status string of the output returned to the client.

SubStatusCode

获取或设置一个限定响应的状态代码的值。Gets or sets a value qualifying the status code of the response.

SupportsAsyncFlush

获取一个值,该值指示集合是否支持异步刷新操作。Gets a value that indicates whether the connection supports asynchronous flush operations.

SuppressContent

获取或设置一个值,该值指示是否将 HTTP 内容发送到客户端。Gets or sets a value indicating whether to send HTTP content to the client.

SuppressDefaultCacheControlHeader

获取或设置一个值,该值指示是否取消默认缓存控件:当前 HTTP 响应的专用标头。Gets or sets a value indicating whether to suppress the default Cache Control: private header for the current HTTP response.

SuppressFormsAuthenticationRedirect

获取或设置指定重定向至登录页的 forms 身份验证是否应取消的值。Gets or sets a value that specifies whether forms authentication redirection to the login page should be suppressed.

TrySkipIisCustomErrors

获取或设置一个值,该值指定是否禁用 IIS 7.0IIS 7.0 自定义错误。Gets or sets a value that specifies whether IIS 7.0IIS 7.0 custom errors are disabled.

方法

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)

使缓存响应的有效性依赖于缓存中的其他项。Makes the validity of a cached response dependent on other items in the cache.

AddCacheItemDependencies(String[])

使缓存项的有效性依赖于缓存中的另一项。Makes the validity of a cached item dependent on another item in the cache.

AddCacheItemDependency(String)

使缓存响应的有效性依赖于缓存中的其他项。Makes the validity of a cached response dependent on another item in the cache.

AddFileDependencies(ArrayList)

将一组文件名添加到文件名集合中,当前响应依赖于该集合。Adds a group of file names to the collection of file names on which the current response is dependent.

AddFileDependencies(String[])

将文件名数组添加到当前响应依赖的文件名集合中。Adds an array of file names to the collection of file names on which the current response is dependent.

AddFileDependency(String)

将单个文件名添加到文件名集合中,当前响应依赖于该集合。Adds a single file name to the collection of file names on which the current response is dependent.

AddHeader(String, String)

将 HTTP 头添加到输出流。Adds an HTTP header to the output stream. 提供 AddHeader(String, String),以便兼容 ASP 的早期版本。AddHeader(String, String) is provided for compatibility with earlier versions of ASP.

AddOnSendingHeaders(Action<HttpContext>)

注册一个回调,在即将为此请求发送响应标头之前,ASP.NET 运行时将会调用此回调。Registers a callback that the ASP.NET runtime will invoke immediately before response headers are sent for this request.

AppendCookie(HttpCookie)

将一个 HTTP Cookie 添加到内部 Cookie 集合。Adds an HTTP cookie to the intrinsic cookie collection.

AppendHeader(String, String)

将 HTTP 头添加到输出流。Adds an HTTP header to the output stream.

AppendToLog(String)

将自定义日志信息添加到 Internet Information Services (IIS)日志文件。Adds custom log information to the Internet Information Services (IIS) log file.

ApplyAppPathModifier(String)

如果会话使用 Cookieless 会话状态,则将该会话 ID 添加到虚拟路径中,并返回组合路径。Adds a session ID to the virtual path if the session is using Cookieless session state and returns the combined path. 如果不使用 Cookieless 会话状态,则 ApplyAppPathModifier(String) 返回原始的虚拟路径。If Cookieless session state is not used, ApplyAppPathModifier(String) returns the original virtual path.

BeginFlush(AsyncCallback, Object)

向客户端发送当前所有缓冲的响应。Sends the currently buffered response to the client.

BinaryWrite(Byte[])

将二进制字符串写入 HTTP 输出流。Writes a string of binary characters to the HTTP output stream.

Clear()

清除缓冲区流中的所有内容输出。Clears all content output from the buffer stream.

ClearContent()

清除缓冲区流中的所有内容输出。Clears all content output from the buffer stream.

ClearHeaders()

清除缓冲区流中的所有头。Clears all headers from the buffer stream.

Close()

关闭到客户端的套接字连接。Closes the socket connection to a client.

DisableKernelCache()

禁用当前响应的内核缓存。Disables kernel caching for the current response.

DisableUserCache()

禁用 IIS 用户-方式来缓存反映。Disables IIS user-mode caching for this response.

End()

将当前所有缓冲的输出发送到客户端,停止该页的执行,并引发 EndRequest 事件。Sends all currently buffered output to the client, stops execution of the page, and raises the EndRequest event.

EndFlush(IAsyncResult)

完成异步刷新操作。Completes an asynchronous flush operation.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
Flush()

向客户端发送当前所有缓冲的输出。Sends all currently buffered output to the client.

FlushAsync()

向客户端异步发送当前缓冲的所有输出。Asynchronously sends all currently buffered output to the client.

GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
Pics(String)

将一个 HTTP PICS-Label 标头追加到输出流。Appends a HTTP PICS-Label header to the output stream.

PushPromise(String)

此 API 用于支持将推送承诺发送到 HTTP 2.0 客户端的应用程序。This API is to support applications sending push promises to HTTP 2.0 clients. 有关 Http2 服务器推送的详细信息,请参阅 HTTP/2 规范第 8.2 节:服务器推送You can find more details regarding to Http2 server push at HTTP/2 Specification Section 8.2: Server Push.

PushPromise(String, String, NameValueCollection)

此 API 用于支持将推送承诺发送到 HTTP 2.0 客户端的应用程序。This API is to support applications sending push promises to HTTP 2.0 clients. 有关 Http2 服务器推送的详细信息,请参阅 HTTP/2 规范第 8.2 节:服务器推送You can find more details regarding to Http2 server push at HTTP/2 Specification Section 8.2: Server Push.

Redirect(String)

将请求重定向到新 URL 并指定该新 URL。Redirects a request to a new URL and specifies the new URL.

Redirect(String, Boolean)

将客户端重定向到新的 URL。Redirects a client to a new URL. 指定新的 URL 并指定当前页的执行是否应终止。Specifies the new URL and whether execution of the current page should terminate.

RedirectPermanent(String)

执行从所请求 URL 到所指定 URL 的永久重定向。Performs a permanent redirection from the requested URL to the specified URL.

RedirectPermanent(String, Boolean)

执行从所请求 URL 到所指定 URL 的永久重定向,并提供用于完成响应的选项。Performs a permanent redirection from the requested URL to the specified URL, and provides the option to complete the response.

RedirectToRoute(Object)

使用路由参数值将请求重定向到新 URL。Redirects a request to a new URL by using route parameter values.

RedirectToRoute(RouteValueDictionary)

使用路由参数值将请求重定向到新 URL。Redirects a request to a new URL by using route parameter values.

RedirectToRoute(String)

使用路由名称将请求重定向到新 URL。Redirects a request to a new URL by using a route name.

RedirectToRoute(String, Object)

使用路由参数值和路由名称将请求重定向到新 URL。Redirects a request to a new URL by using route parameter values and a route name.

RedirectToRoute(String, RouteValueDictionary)

使用路由参数值和路由名称将请求重定向到新 URL。Redirects a request to a new URL by using route parameter values and a route name.

RedirectToRoutePermanent(Object)

使用路由参数值执行从所请求 URL 到新 URL 的永久重定向。Performs a permanent redirection from a requested URL to a new URL by using route parameter values.

RedirectToRoutePermanent(RouteValueDictionary)

使用路由参数值执行从所请求 URL 到新 URL 的永久重定向。Performs a permanent redirection from a requested URL to a new URL by using route parameter values.

RedirectToRoutePermanent(String)

使用路由名称执行从所请求 URL 到新 URL 的永久重定向。Performs a permanent redirection from a requested URL to a new URL by using a route name.

RedirectToRoutePermanent(String, Object)

使用路由参数值以及与新 URL 对应的路由的名称执行从所请求 URL 到新 URL 的永久重定向。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)

使用路由参数值和路由名称执行从所请求 URL 到新 URL 的永久重定向。Performs a permanent redirection from a requested URL to a new URL by using route parameter values and a route name.

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)

使用指定的输出缓存提供程序移除与指定路径关联的所有输出缓存项。Uses the specified output-cache provider to remove all output-cache items that are associated with the specified path.

SetCookie(HttpCookie)

因为 HttpResponse.SetCookie 方法仅供内部使用,所以不应在代码中调用该方法。Because the HttpResponse.SetCookie method is intended for internal use only, you should not call it in your code. 可以改为调用 HttpResponse.Cookies.Set 方法,如以下示例所示。Instead, you can call the HttpResponse.Cookies.Set method, as the following example shows.
更新 Cookie 集合中的一个现有 Cookie。Updates an existing cookie in the cookie collection.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)
TransmitFile(String)

将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件。Writes the specified file directly to an HTTP response output stream, without buffering it in memory.

TransmitFile(String, Int64, Int64)

将文件的指定部分直接写入 HTTP 响应输出流,而不在内存中缓冲它。Writes the specified part of a file directly to an HTTP response output stream without buffering it in memory.

Write(Char)

将一个字符写入 HTTP 响应输出流。Writes a character to an HTTP response output stream.

Write(Char[], Int32, Int32)

将一个字符数组写入 HTTP 响应输出流。Writes an array of characters to an HTTP response output stream.

Write(Object)

Object 写入 HTTP 响应流。Writes an Object to an HTTP response stream.

Write(String)

将一个字符串写入 HTTP 响应输出流。Writes a string to an HTTP response output stream.

WriteFile(IntPtr, Int64, Int64)

将指定的文件直接写入 HTTP 响应输出流。Writes the specified file directly to an HTTP response output stream.

WriteFile(String)

将指定文件的内容作为文件块直接写入 HTTP 响应输出流。Writes the contents of the specified file directly to an HTTP response output stream as a file block.

WriteFile(String, Boolean)

将指定文件的内容作为内存块直接写入 HTTP 响应输出流。Writes the contents of the specified file directly to an HTTP response output stream as a memory block.

WriteFile(String, Int64, Int64)

将指定的文件直接写入 HTTP 响应输出流。Writes the specified file directly to an HTTP response output stream.

WriteSubstitution(HttpResponseSubstitutionCallback)

允许将响应替换块插入响应,从而允许为缓存的输出响应动态生成指定的响应区域。Allows insertion of response substitution blocks into the response, which allows dynamic generation of specified response regions for output cached responses.

适用于