我們研究了頁面生命周期以及頁面如何包含各種控制項。頁面本身被實例化爲一個控制項對象。所有web窗體基本上都是ASP.NET頁類的實例。page類具有與內部對象相對應的以下非常有用的屬性:
- Session
- Application
- Cache
- Request
- Response
- Server
- User
- Trace
我們將在適當的時候討論每一個目標。在本教程中,我們將探討伺服器對象、請求對象和響應對象。
Server Object
Asp.NET中的伺服器對象是System.Web.HttpServerUtility類的實例。HttpServerUtility類提供了許多屬性和方法來執行各種作業。
Properties and Methods of the Server object
HttpServerUtility類的方法和屬性通過ASP.NET提供的內部伺服器對象公開。
下表提供了屬性列表:
Property | Description |
---|---|
MachineName | Name of server computer |
ScriptTimeOut | Gets and sets the request time-out value in seconds. |
下表列出了一些重要的方法:
Method | Description |
---|---|
CreateObject(String) | Creates an instance of the COM object identified by its ProgID (Programmatic ID). |
CreateObject(Type) | Creates an instance of the COM object identified by its Type. |
Equals(Object) | Determines whether the specified Object is equal to the current Object. |
Execute(String) | Executes the handler for the specified virtual path in the context of the current request. |
Execute(String, Boolean) | Executes the handler for the specified virtual path in the context of the current request and specifies whether to clear the QueryString and Form collections. |
GetLastError | Returns the previous exception. |
GetType | Gets the Type of the current instance. |
HtmlEncode | Changes an ordinary string into a string with legal HTML characters. |
HtmlDecode | Converts an Html string into an ordinary string. |
ToString | Returns a String that represents the current Object. |
Transfer(String) | For the current request, terminates execution of the current page and starts execution of a new page by using the specified URL path of the page. |
UrlDecode | Converts an URL string into an ordinary string. |
UrlEncodeToken | Works same as UrlEncode, but on a byte array that contains Base64-encoded data. |
UrlDecodeToken | Works same as UrlDecode, but on a byte array that contains Base64-encoded data. |
MapPath | Return the physical path that corresponds to a specified virtual file path on the server. |
Transfer | Transfers execution to another web page in the current application. |
Request Object
請求對象是System.Web.HttpRequest類的實例。它表示將頁面加載到瀏覽器中的HTTP請求的值和屬性。
此對象所呈現的信息由更高級別的抽象(web控制項模型)包裝。但是,此對象有助於檢查某些信息,如客戶端瀏覽器和cookies。
Properties and Methods of the Request Object
下表提供了請求對象的一些值得注意的屬性:
Property | Description |
---|---|
AcceptTypes | Gets a string array of client-supported MIME accept types. |
ApplicationPath | Gets the ASP.NET application's virtual application root path on the server. |
Browser | Gets or sets information about the requesting client's browser capabilities. |
ContentEncoding | Gets or sets the character set of the entity-body. |
ContentLength | Specifies the length, in bytes, of content sent by the client. |
ContentType | Gets or sets the MIME content type of the incoming request. |
Cookies | Gets a collection of cookies sent by the client. |
FilePath | Gets the virtual path of the current request. |
Files | Gets the collection of files uploaded by the client, in multipart MIME format. |
Form | Gets a collection of form variables. |
Headers | Gets a collection of HTTP headers. |
HttpMethod | Gets the HTTP data transfer method (such as GET, POST, or HEAD) used by the client. |
InputStream | Gets the contents of the incoming HTTP entity body. |
IsSecureConnection | Gets a value indicating whether the HTTP connection uses secure sockets (that is, HTTPS). |
QueryString | Gets the collection of HTTP query string variables. |
RawUrl | Gets the raw URL of the current request. |
RequestType | Gets or sets the HTTP data transfer method (GET or POST) used by the client. |
ServerVariables | Gets a collection of Web server variables. |
TotalBytes | Gets the number of bytes in the current input stream. |
Url | Gets information about the URL of the current request. |
UrlReferrer | Gets information about the URL of the client's previous request that is linked to the current URL. |
UserAgent | Gets the raw user agent string of the client browser. |
UserHostAddress | Gets the IP host address of the remote client. |
UserHostName | Gets the DNS name of the remote client. |
UserLanguages | Gets a sorted string array of client language preferences. |
下表列出了一些重要的方法:
Method | Description |
---|---|
BinaryRead | Performs a binary read of a specified number of bytes from the current input stream. |
Equals(Object) | Determines whether the specified object is equal to the current object. (Inherited from object.) |
GetType | Gets the Type of the current instance. |
MapImageCoordinates | Maps an incoming image-field form parameter to appropriate x-coordinate and y-coordinate values. |
MapPath(String) | Maps the specified virtual path to a physical path. |
SaveAs | Saves an HTTP request to disk. |
ToString | Returns a String that represents the current object. |
ValidateInput | Causes validation to occur for the collections accessed through the Cookies, Form, and QueryString properties. |
Response Object
Response對象表示伺服器對客戶端請求的響應。它是System.Web.HttpResponse類的一個實例。
在ASP.NET中,響應對象在向客戶端發送HTML文本方面沒有任何重要作用,因爲伺服器端控制項具有嵌套的、面向對象的方法來呈現它們自己。
然而,HttpResponse對象仍然提供一些重要的功能,比如cookie特性和Redirect()方法。Response.Redirect()方法允許將用戶轉移到應用程式內外的另一個頁面。它需要往返旅行。
Properties and Methods of the Response Object
下表提供了響應對象的一些值得注意的屬性:
Property | Description |
---|---|
Buffer | Gets or sets a value indicating whether to buffer the output and send it after the complete response is finished processing. |
BufferOutput | Gets or sets a value indicating whether to buffer the output and send it after the complete page is finished processing. |
Charset | Gets or sets the HTTP character set of the output stream. |
ContentEncoding | Gets or sets the HTTP character set of the output stream. |
ContentType | Gets or sets the HTTP MIME type of the output stream. |
Cookies | Gets the response cookie collection. |
Expires | Gets or sets the number of minutes before a page cached on a browser expires. |
ExpiresAbsolute | Gets or sets the absolute date and time at which to remove cached information from the cache. |
HeaderEncoding | Gets or sets an encoding object that represents the encoding for the current header output stream. |
Headers | Gets the collection of response headers. |
IsClientConnected | Gets a value indicating whether the client is still connected to the server. |
Output | Enables output of text to the outgoing HTTP response stream. |
OutputStream | Enables binary output to the outgoing HTTP content body. |
RedirectLocation | Gets or sets the value of the Http Location header. |
Status | Sets the status line that is returned to the client. |
StatusCode | Gets or sets the HTTP status code of the output returned to the client. |
StatusDescription | 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. |
SuppressContent | Gets or sets a value indicating whether to send HTTP content to the client. |
下表列出了一些重要的方法:
Method | Description |
---|---|
AddHeader | Adds an HTTP header to the output stream. AddHeader is provided for compatibility with earlier versions of ASP. |
AppendCookie | Infrastructure adds an HTTP cookie to the intrinsic cookie collection. |
AppendHeader | Adds an HTTP header to the output stream. |
AppendToLog | Adds custom log information to the InterNET Information Services (IIS) log file. |
BinaryWrite | Writes a string of binary characters to the HTTP output stream. |
ClearContent | Clears all content output from the buffer stream. |
Close | Closes the socket connection to a client. |
End | Sends all currently buffered output to the client, stops execution of the page, and raises the EndRequest event. |
Equals(Object) | Determines whether the specified object is equal to the current object. |
Flush | Sends all currently buffered output to the client. |
GetType | Gets the Type of the current instance. |
Pics | Appends a HTTP PICS-Label header to the output stream. |
Redirect(String) | Redirects a request to a new URL and specifies the new URL. |
Redirect(String, Boolean) | Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate. |
SetCookie | Updates an existing cookie in the cookie collection. |
ToString | Returns a String that represents the current Object. |
TransmitFile(String) | Writes the specified file directly to an HTTP response output stream, without buffering it in memory. |
Write(Char) | Writes a character to an HTTP response output stream. |
Write(Object) | Writes an object to an HTTP response stream. |
Write(String) | Writes a string to an HTTP response output stream. |
WriteFile(String) | Writes the contents of the specified file directly to an HTTP response output stream as a file block. |
WriteFile(String, Boolean) | Writes the contents of the specified file directly to an HTTP response output stream as a memory block. |
Example
下面的簡單示例有一個文本框控制項,用戶可以在其中輸入名稱,一個按鈕將信息發送到伺服器,一個標籤控制項顯示客戶端計算機的URL。
內容文件:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="server_side._Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> Enter your name: <br /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Submit" /> <br /> <asp:Label ID="Label1" runat="server"/> </div> </form> </body> </html>
「代碼隱藏」按鈕單擊:
protected void Button1_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(TextBox1.Text)) { // Access the HttpServerUtility methods through // the intrinsic Server object. Label1.Text = "Welcome, " + Server.HtmlEncode(TextBox1.Text) + ". <br/> The url is " + Server.UrlEncode(Request.Url.ToString()) } }
運行該頁可查看以下結果: