﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>C++博客-C++ Programmer's Cookbook-随笔分类-ASP.NET</title><link>http://www.cppblog.com/mzty/category/1773.html</link><description>&lt;br/&gt;  
&lt;br/&gt;
&lt;a href = "http://www.cppblog.com/mzty/archive/2007/03/02/19109.html"&gt;&lt;font size = 5 color ="#00FFFF"&gt;{C++ 基础}&lt;font/&gt;&lt;/a&gt;

&lt;a href = "http://www.cppblog.com/mzty/archive/2007/08/13/29922.html"&gt;&lt;font size = 5 color ="#00FFFF"&gt;{C++ 高级}&lt;font/&gt;&lt;/a&gt;

&lt;a href = "http://www.cppblog.com/mzty/archive/2007/04/16/22064.html"&gt;&lt;font size = 5 color ="#00FFFF"&gt;{C#界面，C++核心算法}&lt;font/&gt;&lt;/a&gt;

&lt;a href = "http://www.cppblog.com/mzty/archive/2007/03/04/19163.html"&gt;&lt;font size = 5 color ="#00FFFF"&gt;{设计模式}&lt;font/&gt;&lt;/a&gt;

&lt;a href = "
http://www.cppblog.com/mzty/archive/2007/03/04/19167.html"&gt;&lt;font size = 5 color ="#FF0000"&gt;{C#基础}&lt;font/&gt;&lt;/a&gt;





</description><language>zh-cn</language><lastBuildDate>Mon, 19 May 2008 15:13:50 GMT</lastBuildDate><pubDate>Mon, 19 May 2008 15:13:50 GMT</pubDate><ttl>60</ttl><item><title>网络编程基础(web application primer (http,html(cgi,isapi),asp,asp.net))</title><link>http://www.cppblog.com/mzty/archive/2006/05/15/7212.html</link><dc:creator>梦在天涯</dc:creator><author>梦在天涯</author><pubDate>Mon, 15 May 2006 09:41:00 GMT</pubDate><guid>http://www.cppblog.com/mzty/archive/2006/05/15/7212.html</guid><wfw:comment>http://www.cppblog.com/mzty/comments/7212.html</wfw:comment><comments>http://www.cppblog.com/mzty/archive/2006/05/15/7212.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/mzty/comments/commentRss/7212.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/mzty/services/trackbacks/7212.html</trackback:ping><description><![CDATA[
		<p class="normal">
				<font size="4">The most proficient developers are those who possess an intimate understanding of the platforms they program and the tools they use to program them. Because it’s difficult to understand how Web forms work if you lack a more general understanding of Web applications and the protocols that drive them, the next several sections provide a working introduction to the operation of Web apps. They’re for developers who have little or no Web programming experience. If you’re already familiar with HTTP, HTML forms, and other Web-related technologies, feel free to skip ahead to the section entitled “Your First Web Form.” If, however, Web apps are a new frontier for you, you’ll find the following discussion helpful in building an in-depth understanding of the Web Forms programming model.</font>
		</p>
		<div class="bb">
				<div class="title">
						<font style="BACKGROUND-COLOR: #ff1493" size="4">Hypertext Transfer Protocol</font>
				</div>
				<p class="normal">
						<font size="4">The Hypertext Transfer Protocol, better known as HTTP, is the protocol that drives the World Wide Web. Invented by Tim Berners-Lee ("father of the Web") and documented in RFC 2068, which is available online at </font>
						<a class="url" href="http://www.w3.org/Protocols/rfc2068/rfc2068" target="_window2">
								<font size="4">www.w3.org/Protocols/rfc2068/rfc2068</font>
						</a>
						<font size="4">, HTTP is arguably the most important network protocol ever invented, with the notable exception of TCP/IP.</font>
				</p>
				<p class="normal">
						<font size="4">
								<font style="BACKGROUND-COLOR: #ff1493">HTTP defines how Web browsers and Web servers communicate with each other</font>. <font style="BACKGROUND-COLOR: #ff1493">It’s entirely text based</font>, <font style="BACKGROUND-COLOR: #ff1493">and it’s typically transmitted over TCP connections linking Web browsers to Web servers</font>. Suppose the following HTML file is deployed on a Web server, that its name is Simple.html, and that its URL is <span class="emphasis">www.wintellect.com/simple.html</span>:</font>
						<br />
						<font size="4">&lt;html&gt;<br />&lt;body&gt;<br />Hello, world<br />&lt;/body&gt;<br />&lt;/html&gt;</font>
						<br />
				</p>
				<p class="normal">
						<font size="4">If a user types <span class="emphasis">http://www.wintellect.com/simple.html</span> into Internet Explorer’s address bar, Internet Explorer (IE) uses the Internet’s Domain Name System (DNS) to convert <span class="emphasis">www.wintellect.com</span> into an IP address (for example, 66.45.26.25). Then IE opens <font style="BACKGROUND-COLOR: #ff1493">a socket connection</font> to the server at that address using a well-known port number (port 80) and transmits an HTTP request similar to this one:</font>
						<br />
						<font color="#ff1493" size="4">GET /simple.html HTTP/1.1<br />Accept: */*<br />Accept-Language: en-us<br />Accept-Encoding: gzip, deflate<br />If-Modified-Since: Wed, 24 Oct 2001 14:12:36 GMT<br />If-None-Match: "50b0d3ee955cc11:a78"<br />User-Agent: Mozilla/4.0.(compatible; MSIE.6.0; Windows NT 5.1)<br />Host: www.wintellect.com<br />Connection: Keep-Alive<br />[blank line]</font>
						<br />
				</p>
				<p class="normal">
						<font size="4">The first line of the request is called the <span class="emphasis">start line</span>. It consists of a method name (GET), the name of the resource being requested (simple.html), and an HTTP version number (1.1). GET is one of seven methods defined in HTTP 1.1; it requests a resource from a Web server. The next eight lines make up the <span class="emphasis">message header</span>. Each line, or <span class="emphasis">header</span>, contains additional information about the request, including information about the browser that originated the request (<span class="programelement">User-Agent</span>). A blank line (a simple carriage return/line feed pair) marks the end of the message header and also the end of the request.</font>
				</p>
				<p class="normal">
						<font size="4">How does<font style="BACKGROUND-COLOR: #ff1493"> the Web server respond to the GET command</font>? Assuming /simple.html is a valid resource identifier and security settings don’t prevent the file from being returned, the server transmits an HTTP response like this one:</font>
						<br />
						<font color="#ff1493" size="4">HTTP/1.1 200 OK<br />Server: Microsoft-IIS/5.0<br />Date: Wed, 24 Oct 2001 14:12:37 GMT<br />Content-Type: text/html<br />Accept-Ranges: bytes<br />Last-Modified: Wed, 24 Oct 2001 14:00:53 GMT<br />ETag: "d02acf81975cc11:a78"<br />Content-Length: 46<br />[blank line]<br />&lt;html&gt;<br />&lt;body&gt;<br />Hello, world<br />&lt;/body&gt;<br />&lt;/html&gt;</font>
						<br />
				</p>
				<p class="continuation">
						<font size="4">Upon receiving the response, the browser parses the HTML returned by the Web server and displays the resulting Web page. The <span class="programelement">Content-Type</span> header identifies the returned data as HTML, while <span class="programelement">Content-Length</span> tells the browser how much HTML was returned. The “200” in the first line of the response is an HTTP status code signifying that the server fulfilled the browser’s request. The HTTP specification defines about 40 different status codes, including the infamous 401 (“Unauthorized”) code indicating that the user isn’t authorized to view this resource.</font>
				</p>
				<p class="normal">
						<font size="4">Conversations such as these form the backbone for communications over the Web. As you surf the Web by typing URLs and clicking hyperlinks, your browser issues one GET command after another. Tools such as NetMon—the network packet-sniffing utility that comes with server editions of Windows—let you spy on the HTTP traffic flying back and forth. You don’t have to be an HTTP guru to write ASP.NET applications, but a knowledge of basic HTTP semantics and a familiarity with commonly used request and response headers are a big help in understanding the ASP.NET object model.</font>
				</p>
		</div>
		<div class="bb">
				<div class="title">
						<font style="BACKGROUND-COLOR: #ff1493" size="4">HTML Forms</font>
				</div>
				<p class="normal">
						<font size="4">Simple.html is a far cry from a full-blown Web application. It’s a static HTML file that solicits no user input. Real Web applications like the ones located at </font>
						<a class="url" href="http://www.amazon.com/" target="_window2">
								<font size="4">www.amazon.com</font>
						</a>
						<font size="4">and </font>
						<a class="url" href="http://www.ebay.com/" target="_window2">
								<font size="4">www.ebay.com</font>
						</a>
						<font size="4">accept input from their users, and they vary the HTML that they return to Web browsers based on the contents of that input.</font>
				</p>
				<p class="normal">
						<font size="4">At the heart of almost every genuine Web application is an HTML form. An HTML form is the portion of an HTML document that appears between &lt;form&gt; and &lt;/form&gt; tags. The HTML in Figure 5-1 describes a simple form representing a Web-based adding machine. The form contains two text input fields for the user to type numbers into and an equals button that submits the form back to the server. Figure 5-2 shows how the form appears in Internet Explorer. As you can see, the browser renders an &lt;input type=“text”&gt; tag as a text input field and an &lt;input type=“submit”&gt; tag as a push button. Similar tags can be used to create check boxes, radio buttons, list boxes, and other basic control types.</font>
				</p>
				<div class="codeblock_numbered">
						<div class="title">
								<font size="4">Calc.html</font>
								<br />
								<font size="4">&lt;html&gt;<br />  &lt;body&gt;<br />    &lt;form&gt;<br />      &lt;input type="text" name="op1" /&gt;<br />      +<br />      &lt;input type="text" name="op2" /&gt;<br />      &lt;input type="submit" value="  =  " /&gt;<br />    &lt;/form&gt;<br />  &lt;/body&gt;<br />&lt;/html&gt;</font>
								<br />
						</div>
						<font size="4">
								<span class="fignum">Figure 5-1</span>
						</font>
						<div class="caption">
								<font size="4">A simple HTML form.</font>
						</div>
				</div>
				<div class="exhibit" title="Click to view full size" align="center" alt="Graphic Image - ">
						<font size="4">
								<img style="FILTER: blur(strength=2); CURSOR: hand" src="mk:@MSITStore:C:\Documents%20and%20Settings\xhzhu\Desktop\Programming%20Microsoft%20.NET%20(core%20reference).chm::/netcorehtml/images/F05om02.jpg" width="404" />
								<span class="fignum">Figure 5-2</span>
						</font>
						<div class="caption">
								<font size="4">Calc.html displayed in Internet Explorer.</font>
						</div>
				</div>
				<p class="normal">
						<font size="4">A submit button (&lt;input type=“submit”&gt;) plays a special role in an HTML form. When clicked, it submits the form to a Web server. <font color="#ff1493">To be more precise, the <span class="emphasis">browser</span> submits the form along with any input in the form’s controls</font>. How the form is submitted depends on whether the &lt;form&gt; tag includes a <span class="programelement">Method</span> attribute and the value of that attribute, if present. If the &lt;form&gt; tag lacks a <span class="programelement">Method</span> attribute or includes <font style="BACKGROUND-COLOR: #ff1493">a <span class="programelement">method=</span>“get” attribute</font>, <font style="BACKGROUND-COLOR: #ff1493">the browser sends an HTTP GET command to the server with the user’s input appended to the URL in the form of a query string:</font></font>
						<br />
						<font color="#ff1493" size="4">GET /calc.html?op1=2&amp;op2=2 HTTP/1.1<br />  .<br />  .<br />  .<br />Connection: Keep-Alive<br />[blank line]</font>
						<br />
				</p>
				<p class="continuation">
						<font size="4">If, on the other hand, the &lt;form&gt; tag includes <font style="BACKGROUND-COLOR: #ff1493">a <span class="programelement">method=</span>“post” attribute</font>, <font style="BACKGROUND-COLOR: #ff1493">the form is submitted to the server using an HTTP POST command. Rather than transmit user input in the URL, with a POST command the browser passes it in the body of the HTTP request:</font></font>
						<br />
						<font color="#ff1493" size="4">POST /calc.html HTTP/1.1<br />  .<br />  .<br />  .<br />Content-Type: application/x-www-form-urlencoded<br />Content-Length: 11<br />[blank line]<br />op1=2&amp;op2=2</font>
						<br />
				</p>
				<p class="continuation">
						<font size="4">Regardless of whether a GET or a POST command is used, when input from an HTML form is submitted back to the server, we say that a <font style="BACKGROUND-COLOR: #ff1493">“postback”</font> has occurred. Remember that term because you’ll encounter it repeatedly in this and the next several chapters.</font>
				</p>
				<p class="normal">
						<font size="4">For a first-hand look at HTML forms in action, copy Calc.html to your PC’s \Inetpub\wwwroot directory and call it up in Internet Explorer by typing the following URL:</font>
						<br />
						<font size="4">
								<a href="http://localhost/calc.html">http://localhost/calc.html</a>
								<br />
						</font>
						<br />
				</p>
				<p class="continuation">
						<font size="4">Now type 2 into each of the form’s text boxes and click the = button. As evidence that a postback occurred, observe what appears in the browser’s address bar (shown in Figure 5-3). If you change the &lt;form&gt; tag to</font>
						<br />
						<br />
						<font size="4">&lt;form method="post"&gt;</font>
						<br />
				</p>
				<p class="continuation">
						<font size="4">and repeat the experiment, you won’t see any change in the URL. But the postback occurs just the same, and the Web server can access the user’s input by examining the body of the request.</font>
				</p>
				<div class="exhibit" title="Click to view full size" align="center" alt="Graphic Image - ">
						<font size="4">
								<img style="FILTER: blur(strength=2); CURSOR: hand" src="mk:@MSITStore:C:\Documents%20and%20Settings\xhzhu\Desktop\Programming%20Microsoft%20.NET%20(core%20reference).chm::/netcorehtml/images/F05om03.jpg" width="404" />
								<span class="fignum">Figure 5-3</span>
						</font>
						<div class="caption">
								<font size="4">Calc.html following a postback.</font>
						</div>
				</div>
		</div>
		<div class="bb">
				<div class="title">
						<font style="BACKGROUND-COLOR: #ffffff" color="#0000ff" size="4">Server-Side Processing(cgi &amp;&amp;isipi)</font>
				</div>
				<p class="normal">
						<font size="4">So far, so good. As Calc.html demonstrates, building the client half of a Web application is easy. After all, it’s just HTML. The hard part is building the code that runs on the Web server. <span class="emphasis">Something</span> has to be running there to extract the user input from the URL (or from the body of the HTTP request if the postback was performed with POST instead of GET) and generate a new Web page that displays the sum of the inputs next to the = button. In other words, if the user enters 2 and 2 and clicks the = button, we’d like the Web server to respond by returning the following HTML:</font>
						<br />
						<br />
						<font size="4">&lt;html&gt;<br />  &lt;body&gt;<br />    &lt;form&gt;<br />      &lt;input type="text" name="op1" value="2" /&gt;<br />      +<br />      &lt;input type="text" name="op2" value="2" /&gt;<br />      &lt;input type="submit" value="  =  " /&gt;<br />      4<br />    &lt;/form&gt;<br />  &lt;/body&gt;<br />&lt;/html&gt;</font>
						<br />
				</p>
				<p class="continuation">
						<font size="4">Note the <span class="programelement">Value</span> attributes added to the &lt;input type=“text”&gt; tags. Including the inputs in the page returned from the Web server following a postback perpetuates the illusion that the user is seeing one Web page when in fact he or she is seeing two in succession.</font>
				</p>
				<p class="normal">
						<font size="4">
								<font style="BACKGROUND-COLOR: #ff1493">There are many ways to write applications that process input from HTML forms.</font> One solution is an application that uses the Common Gateway Interface (CGI). <font style="BACKGROUND-COLOR: #ff1493">CGI defines a low-level programmatic interface between Web servers and applications that run on Web servers.</font> Applications that use it are typically written in a programming language called Perl, but they can be written in other languages as well. <font style="BACKGROUND-COLOR: #ff1493">CGI applications read the input accompanying postbacks through server environment variables and standard input (stdin), and they write HTTP responses to standard output (stdout).</font><font style="BACKGROUND-COLOR: #ffff00">CGI has a reputation for being slow because many implementations of it launch a new process to handle each incoming request.</font> Despite this, CGI enjoys widespread use on UNIX-based Web servers. It’s rarely used on the Windows platform.</font>
				</p>
				<p class="normal">
						<font size="4">Another solution—one that’s more likely to find favor among Windows developers—is an ISAPI extension DLL. <font style="BACKGROUND-COLOR: #ff1493">ISAPI stands for Internet Server Application Programming Interface. ISAPI extensions are Windows DLLs that are hosted by Internet Information Services.</font> They’re referenced by URL just like HTML files (for example, <span class="emphasis">http://www.wintellect.com/calc.dll</span>). <font style="BACKGROUND-COLOR: #ff1493">IIS forwards HTTP requests to an ISAPI DLL by calling a special function exported from the DLL. The DLL, in turn, generates HTTP responses.</font><font style="BACKGROUND-COLOR: #ffff00" color="#000000">ISAPI DLLs are faster than CGI applications because they (typically) run in the same process as IIS</font>. And once loaded, they remain in memory awaiting subsequent requests. The downside to ISAPI DLLs is that they’re difficult to write. An ISAPI developer must be comfortable with the architecture of Windows DLLs and also be willing to deal with HTTP messages at a very low level.</font>
				</p>
				<p class="normal">
						<font size="4">Curious to know what an ISAPI DLL looks like? Figure 5-4 shows the C++ source code for an ISAPI DLL that implements a Web calculator identical to the one shown in Figure 5-2. The heart of the DLL is the <span class="programelement">HttpExtensionProc</span> function, which IIS calls on each and every request. The <span class="programelement">pECB</span> parameter points to a structure containing information about the request, including a pointer to the query string (if any) accompanying the request. If the query string is empty, this implementation of <span class="programelement">HttpExtensionProc</span> returns an HTML page depicting an empty calculator. Following a postback, however, it parses the <span class="programelement">op1</span> and <span class="programelement">op2</span> parameters from the query string and returns an HTML page that includes the sum of the inputs. In other words, it returns precisely the HTML we set as our goal a moment ago.<br /></font>
				</p>
				<div class="codeblock_numbered">
						<div class="title">
								<font size="4">
										<font style="BACKGROUND-COLOR: #7fffd4">ISIPI实现:<br /></font>Calc.cpp</font>
								<br />
								<br />
								<font size="4">#include &lt;windows.h&gt;<br />#include &lt;httpext.h&gt;<br />#include &lt;string.h&gt;<br />#include &lt;stdlib.h&gt;</font>
								<br />
								<font size="4">
										<br />int GetParameter (LPSTR pszQueryString, LPSTR pszParameterName);<br /><br />BOOL WINAPI DllMain (HINSTANCE hInstance, DWORD fdwReason,<br />    LPVOID lpvReserved)<br />{<br />    return (TRUE);<br />}<br /><br />BOOL WINAPI GetExtensionVersion (HSE_VERSION_INFO* pVer)<br />{<br />    pVer-&gt;dwExtensionVersion = <br />        MAKELONG (HSE_VERSION_MINOR, HSE_VERSION_MAJOR);<br />    lstrcpy (pVer-&gt;lpszExtensionDesc, "Calc ISAPI Extension");<br />    return (TRUE);<br />}<br /><br />DWORD WINAPI HttpExtensionProc (EXTENSION_CONTROL_BLOCK* pECB)<br />{<br />    static char* szPrePostbackMessage = <br />        "&lt;html&gt;\r\n"                                    \<br />        "&lt;body&gt;\r\n"                                    \<br />        "&lt;form&gt;\r\n"                                    \<br />        "&lt;input type=\"text\" name=\"op1\" /&gt;\r\n"      \<br />        "+\r\n"                                         \<br />        "&lt;input type=\"text\" name=\"op2\" /&gt;\r\n"      \<br />        "&lt;input type=\"submit\" value=\"  =  \" /&gt;\r\n" \<br />        "&lt;/form&gt;\r\n"                                   \<br />        "&lt;/body&gt;\r\n"                                   \<br />        "&lt;/html&gt;";<br /><br />    static char* szPostPostbackMessage = <br />        "&lt;html&gt;\r\n"                                            \<br />        "&lt;body&gt;\r\n"                                            \<br />        "&lt;form&gt;\r\n"                                            \<br />        "&lt;input type=\"text\" name=\"op1\" value=\"%d\" /&gt;\r\n" \<br />        "+\r\n"                                                 \<br />        "&lt;input type=\"text\" name=\"op2\" value=\"%d\" /&gt;\r\n" \<br />        "&lt;input type=\"submit\" value=\"  =  \" /&gt;\r\n"         \<br />        "%d\r\n"                                                \<br />        "&lt;/form&gt;\r\n"                                           \<br />        "&lt;/body&gt;\r\n"                                           \<br />        "&lt;/html&gt;";<br /><br />    //<br />    // Build the response message body.<br />    //<br />    char szMessage[512];<br /><br />    if (lstrlen (pECB-&gt;lpszQueryString) == 0) {<br />        // If the query string is empty, return a page that shows<br />        // an empty calculator.<br />        lstrcpy (szMessage, szPrePostbackMessage);<br />    }<br />    else {<br />        // If the query string is not empty, extract the user input,<br />        // process it, and return a page that shows inputs and outputs.<br />        int a = GetParameter (pECB-&gt;lpszQueryString, "op1");<br />        int b = GetParameter (pECB-&gt;lpszQueryString, "op2");<br />        wsprintf (szMessage, szPostPostbackMessage, a, b, a + b);<br />    }<br /><br />    //<br />    // Build the response message header.<br />    //<br />    char szHeader[128];<br />    DWORD dwCount = lstrlen (szMessage);<br /><br />    wsprintf (szHeader, "Content-type: text/html\r\n" \<br />        "Content-Length: %lu\r\n\r\n", dwCount);<br /><br />    //<br />    // Output the response message header.<br />    //<br />    HSE_SEND_HEADER_EX_INFO shei;<br />    shei.pszStatus = "200 OK";<br />    shei.pszHeader = szHeader;<br />    shei.cchStatus = lstrlen (shei.pszStatus);<br />    shei.cchHeader = lstrlen (shei.pszHeader);<br />    shei.fKeepConn = FALSE;<br /><br />    pECB-&gt;ServerSupportFunction (pECB-&gt;ConnID,<br />        HSE_REQ_SEND_RESPONSE_HEADER_EX, &amp;shei, NULL, NULL);  <br /><br />    //<br />    // Output the response message body.<br />    //<br />    pECB-&gt;WriteClient (pECB-&gt;ConnID, szMessage, &amp;dwCount, 0); <br /><br />    //<br />    // Indicate that the request was processed successfully.<br />    //<br />    return HSE_STATUS_SUCCESS;<br />}<br /><br />int GetParameter (LPSTR pszQueryString, LPSTR pszParameterName)<br />{<br />    char* p = strstr (pszQueryString, pszParameterName);<br /><br />    if (p != NULL) {<br />        p += strlen (pszParameterName) + 1;<br />        for (char* tmp = p; *tmp != '&amp;' &amp;&amp; *tmp != 0; tmp++)<br />            ;<br />        int len = tmp - p;<br />        char* buffer = new char[len + 1];<br />        strncpy (buffer, p, len);<br />        int val = atoi (buffer);<br />        delete buffer;<br />        return val;<br />    }<br />    return 0;<br />}</font>
								<br />
						</div>
				</div>
				<font size="4">
						<span class="fignum">Figure 5-4</span>
				</font>
				<div class="caption">
						<font style="BACKGROUND-COLOR: #7fffd4" size="4">Source code for an ISAPI DLL.<br /><br /></font>
				</div>
		</div>
		<div class="bb">
				<div class="title">
						<font style="BACKGROUND-COLOR: #ff1493" size="4">The Active Server Pages Solution</font>
				</div>
				<p class="normal">
						<font size="4">A third solution to the problem of processing input from HTML forms on Web servers, and the one that made Windows a popular platform for Web applications in the second half of the 1990s, is Active Server Pages (ASP). Active Server Pages lower the barrier to entry for Web developers by allowing HTML and server-side script to be freely mixed in ASP files. Scripts are typically written in JScript (Microsoft’s version of JavaScript) or VBScript, but they can be written in other languages as well. Intrinsic objects available to those scripts abstract the low-level details of HTTP and make it exceedingly easy to write code that generates HTML content dynamically. Just how easy is ASP? Compare the code in Figures 5-4 and 5-5 and judge for yourself.</font>
				</p>
				<p class="normal">
						<font size="4">When an Active Server Page is requested, ASP parses the page and executes any scripts contained inside it. <font style="BACKGROUND-COLOR: #ff1493">Scripts access the input accompanying the request by using the ASP <span class="programelement">Request</span> object, and they write HTML to the HTTP response using the ASP <span class="programelement">Response</span> object.</font> Figure 5-5 shows the ASP version of Calc.html. The VBScript between &lt;% and %&gt; tags checks the incoming request for inputs named <span class="programelement">op1</span> and <span class="programelement">op2</span>. If the inputs aren’t present, an empty calculator is rendered back to the client. If the inputs are present—that is, if <span class="programelement">Request (“op1”)</span> and <span class="programelement">Request (“op2”)</span> evaluate to non-null strings—the server-side script converts the inputs to integers, adds them together, converts the result to a string, and writes the string to the HTTP response using <span class="programelement">Response.Write</span>.</font>
				</p>
				<p class="normal">
						<font size="4">To prevent the numbers typed into the text boxes from disappearing following a postback, Calc.asp uses ASP’s inline output syntax (&lt;%= … %&gt;) to initialize the <span class="programelement">Value</span> attributes returned in the &lt;input type=“text”&gt; tags. When the page is first requested from the server, <span class="programelement">Request (“op1”)</span> and <span class="programelement">Request (“op2”)</span> return empty strings, so the tags output to the client produce empty text boxes:</font>
						<font size="4">&lt;input type="text" name="op1" value=""/&gt;<br />&lt;input type="text" name="op2" value=""/&gt;</font>
						<br />
				</p>
				<p class="continuation">
						<font size="4">But when the form is rendered again following a postback, <span class="programelement">Request (“op1”)</span> and <span class="programelement">Request (“op2”)</span> return the values input by the user and are echoed to the client in the tags’ <span class="programelement">Value</span> attributes:</font>
						<br />
						<font size="4">&lt;input type="text" name="op1" value="2"/&gt;<br />&lt;input type="text" name="op2" value="2"/&gt;</font>
						<br />
				</p>
				<p class="normal">
						<font size="4">To verify that this is the case, drop Calc.asp into \Inetpub\wwwroot and bring it up by typing <span class="programelement">http://localhost/calc.asp</span>. Then enter a couple of numbers, click the = button, and use the View/Source command in Internet Explorer to view the HTML returned by ASP.</font>
				</p>
				<p class="normal">
						<font size="4">The appeal of ASP—and the reason it caught on so quickly after its introduction in 1996—is that it provides an easy-to-use model for dynamically generating HTML on Web servers. ASP provides a higher level of abstraction than either CGI or ISAPI, which means a flatter learning curve and faster time to market. And ASP integrates seamlessly with ActiveX Data Objects (ADO), which makes it a great solution for writing Web apps that interact with back-end databases.</font>
				</p>
				<div class="codeblock_numbered">
						<div class="title">
								<font size="4">Calc.asp</font>
								<br />
								<br />
								<font size="4">&lt;%@ Language="VBScript" %&gt;<br /><br />&lt;html&gt;<br />  &lt;body&gt;<br />    &lt;form&gt;<br />      &lt;input type="text" name="op1" value="&lt;%= Request ("op1") %&gt;"/&gt;<br />      +<br />      &lt;input type="text" name="op2" value="&lt;%= Request ("op2") %&gt;" /&gt;<br />      &lt;input type="submit" value="  =  " /&gt;<br />      <font color="#ff1493">&lt;%<br />        If Request ("op1") &lt;&gt; "" And Request ("op2") &lt;&gt; "" Then<br />            a = CInt (Request ("op1"))<br />            b = CInt (Request ("op2"))<br />            Response.Write (CStr (a + b))<br />        End If<br />      %&gt;</font><br />    &lt;/form&gt;<br />  &lt;/body&gt;<br />&lt;/html&gt;</font>
								<br />
						</div>
						<font size="4">
								<span class="fignum">Figure 5-5</span>
						</font>
						<div class="caption">
								<font style="BACKGROUND-COLOR: #7fffd4" size="4">ASP calculator applet.<br /><br /></font>
						</div>
				</div>
		</div>
		<div class="bb">
				<div class="title">
						<font style="BACKGROUND-COLOR: #ff1493" size="4">Your First Web Form</font>
				</div>
				<p class="normal">
						<font size="4">ASP is a fine solution for performing server-side processing of HTML form input and dynamically generating HTML, but despite its youth, ASP has already grown long in the tooth. What’s wrong with ASP? For starters, it’s slow. ASP scripts are interpreted rather than compiled, so you incur the cost of recompiling your scripts on each and every page access. Another problem is that ASP lacks a true encapsulation model. It’s not possible, for example, to build reusable ASP controls that encapsulate complex rendering and behavioral logic without resorting to COM.</font>
				</p>
				<p class="normal">
						<font size="4">Enter ASP.NET Web forms. Web forms bring object-oriented programming to the Web. They also combine ASP’s ease of use with the speed of compiled code. Figure 5-6 holds the source code for the Web Forms version of Calc.asp. The .aspx file name extension identifies the file as an ASP.NET resource. Figure 5-7 shows how Calc.aspx appears in Internet Explorer. Here’s how to run it on your PC:</font>
				</p>
				<ol>
						<li>
								<p class="normal">
										<font size="4">Copy Calc.aspx to your PC’s \Inetpub\wwwroot directory.</font>
								</p>
						</li>
						<li>
								<p class="normal">
										<font size="4">Start Internet Explorer or the browser of your choice and type <span class="programelement">http://localhost/calc.aspx</span> in the browser’s address bar. The Web form will appear in the browser window.</font>
								</p>
						</li>
						<li>
								<p class="normal">
										<font size="4">Type 2 and 2 into the input fields and click the = button. The number 4 should appear to the right of the button.</font>
								</p>
						</li>
				</ol>
				<p class="normal">
						<font size="4">The \Inetpub\wwwroot directory is an IIS virtual directory; it’s created automatically when you install IIS. If you’d prefer not to clutter \Inetpub\wwwroot, you can set up virtual directories of your own using the Internet Services Manager applet found under Administrative Tools. You could, for example, put Calc.aspx in a directory named Samples and make Samples a virtual directory. If you assign the Samples directory the logical name “Samples” (virtual directory names don’t have to equal physical directory names, although they often do), you’d run Calc by typing <span class="emphasis">http://localhost/samples/calc.aspx</span> in the browser’s address bar. The same goes for other ASPX files presented in this chapter and throughout the remainder of the book.</font>
				</p>
				<div class="codeblock_numbered">
						<div class="title">
								<font size="4">Calc.aspx</font>
								<br />
								<br />
								<font size="4">&lt;html&gt;<br />  &lt;body&gt;<br />    &lt;form runat="server"&gt;<br />      &lt;asp:TextBox ID="op1" RunAt="server" /&gt;<br />      +<br />      &lt;asp:TextBox ID="op2" RunAt="server" /&gt;<br />      &lt;asp:Button Text="  =  " OnClick="OnAdd" RunAt="server" /&gt;<br />      &lt;asp:Label ID="Sum" RunAt="server" /&gt;<br />    &lt;/form&gt;<br />  &lt;/body&gt;<br />&lt;/html&gt;<br /><br /><font color="#ff1493">&lt;script language="C#" runat="server"&gt;<br />  void OnAdd (Object sender, EventArgs e)<br />  {<br />      int a = Convert.ToInt32 (op1.Text);<br />      int b = Convert.ToInt32 (op2.Text);<br />      Sum.Text = (a + b).ToString ();<br />  }<br />&lt;/script&gt;</font></font>
								<br />
						</div>
						<font size="4">
								<span class="fignum">Figure 5-6</span>
						</font>
						<div class="caption">
								<font size="4">ASP.NET Web form calculator.</font>
						</div>
				</div>
				<div class="exhibit" title="Click to view full size" align="center" alt="Graphic Image - ">
						<font size="4">
								<img style="FILTER: blur(strength=2); CURSOR: hand" src="mk:@MSITStore:C:\Documents%20and%20Settings\xhzhu\Desktop\Programming%20Microsoft%20.NET%20(core%20reference).chm::/netcorehtml/images/F05om07.jpg" width="404" />
								<span class="fignum">Figure 5-7</span>
						</font>
						<div class="caption">
								<font size="4">Calc.aspx in action.</font>
						</div>
				</div>
				<p class="normal">
						<font size="4">Web forms are built from a combination of HTML and server controls. Calc.aspx contains four server controls: two <span class="programelement">TextBox</span> controls, a <span class="programelement">Button</span> control, and a <span class="programelement">Label</span> control. <span class="programelement">TextBox</span>, <span class="programelement">Button</span>, and <span class="programelement">Label</span> are classes defined in the <span class="programelement">System.Web.UI.WebControls</span> namespace in the .NET Framework class library (FCL). Each time Calc.aspx is requested, ASP.NET instantiates <span class="programelement">TextBox</span>, <span class="programelement">Button</span>, and <span class="programelement">Label</span> objects and asks each object to render itself into HTML. The HTML returned by the controls is included in the HTTP response. Execute a View/Source command while Calc.aspx is displayed in Internet Explorer and you’ll see the following HTML:</font>
						<font size="4">&lt;html&gt;<br />  &lt;body&gt;<br />    &lt;form name="_ctl0" method="post" action="calc.aspx" id="_ctl0"&gt;<br />      &lt;input type="hidden" name="__VIEWSTATE" value="dDwxOTE0NDY4ODE2Ozs+" /&gt;<br /><br />      &lt;input name="op1" type="text" id="op1" /&gt;<br />      +<br />      &lt;input name="op2" type="text" id="op2" /&gt;<br />      &lt;input type="submit" name="_ctl1" value="  =  " /&gt;<br />      &lt;span id="Sum"&gt;&lt;/span&gt;<br />    &lt;/form&gt;<br />  &lt;/body&gt;<br />&lt;/html&gt;</font>
						<br />
				</p>
				<p class="continuation">
						<font size="4">The <span class="programelement">TextBox</span> controls turned into &lt;input type=“text”&gt; tags, the <span class="programelement">Button</span> control turned into an &lt;input type=“submit”&gt; tag, and the <span class="programelement">Label</span> control turned into a &lt;span&gt; tag. In effect, these controls “project” a user interface to the browser by rendering themselves into HTML.</font>
				</p>
				<p class="normal">
						<font size="4">What about the &lt;input&gt; tag named __VIEWSTATE in the HTML returned by Calc.aspx? That’s the mechanism ASP.NET uses to round-trip data from the server to the client and back to the server again. You’ll learn all about it in Chapter 8.</font>
				</p>
				<div class="cc">
						<div class="title">
								<font size="4">Control Properties</font>
						</div>
						<p class="normal">
								<font size="4">Server controls do more than render HTML. They also implement methods, properties, and events that make them highly programmable. For example, <span class="programelement">TextBox</span>, <span class="programelement">Button</span>, and <span class="programelement">Label</span> controls each expose text through a read/write property named <span class="programelement">Text</span>. If you wanted “2” to appear in the <span class="programelement">TextBox</span> controls by default, you could modify the control tags as follows:</font>
								<br />
								<font size="4">&lt;asp:TextBox Text="2" ID="op1" RunAt="server" /&gt;<br />&lt;asp:TextBox Text="2" ID="op2" RunAt="server" /&gt;</font>
								<br />
						</p>
						<p class="continuation">
								<font size="4">Any public property that a control implements and that can be represented as a name/value pair can be initialized by using the property name as an attribute in the tag that declares the control.</font>
						</p>
						<p class="normal">
								<font size="4">Properties can also be accessed from server-side scripts. In Calc.aspx, the server-side script is the code that appears between the &lt;script&gt; and &lt;/script&gt; tags. The statements</font>
								<br />
								<br />
								<font size="4">int a = Convert.ToInt32 (op1.Text);<br />int b = Convert.ToInt32 (op2.Text);</font>
								<br />
						</p>
						<p class="continuation">
								<font size="4">extract user input from the <span class="programelement">TextBox</span> controls by reading their <span class="programelement">Text</span> properties, while the statement</font>
								<br />
								<font size="4">Sum.Text = (a + b).ToString ();</font>
								<br />
						</p>
						<p class="continuation">
								<font size="4">displays the sum of the inputs by writing to the <span class="programelement">Label</span> control’s <span class="programelement">Text</span> property. The names <span class="programelement">op1</span>, <span class="programelement">op2</span>, and <span class="programelement">Sum</span> are the controls’ programmatic IDs. Control IDs are defined by including <span class="programelement">ID</span> attributes in control tags. In Calc.aspx, the <span class="programelement">Label</span> control serves as a placeholder for the Web form’s output. Because the default value of a <span class="programelement">Label</span> control’s <span class="programelement">Text</span> property is an empty string, nothing appears in the form where the <span class="programelement">Label</span> control is positioned until the server-side script assigns a string to the <span class="programelement"></span>control’s <span class="programelement">Text</span> property.</font>
						</p>
				</div>
				<div class="cc">
						<div class="title">
								<font size="4">Control Events</font>
						</div>
						<p class="normal">
								<font size="4">The ability to encapsulate complex rendering and behavioral logic in reusable control classes is one of the fundamental tenets of the Web Forms programming model. Another is the use of events and event handling. Most server controls fire events in response to user input. <span class="programelement">Button</span> controls, for example, fire <span class="programelement">Click</span> events when they’re clicked. Wiring an event to an event handler is accomplished by prefixing the event name with “On” and using the resulting text as an attribute in the tag that declares the control. In Calc.aspx, the statement</font>
								<br />
								<br />
								<font size="4">&lt;asp:Button Text="  =  " OnClick="OnAdd" RunAt="server" /&gt;</font>
								<br />
						</p>
						<p class="continuation">
								<font size="4">serves the dual purpose of declaring a <span class="programelement">Button</span> control and designating <span class="programelement">OnAdd</span> as the handler for the <span class="programelement">Button</span> control’s <span class="programelement">Click</span> events. That’s why the code in <span class="programelement">OnAdd</span> executed when you clicked the = button. Knowing this, it’s a simple matter to consult the documentation for the list of events a control is capable of firing and connecting handlers to the events that interest you.</font>
						</p>
						<p class="normal">
								<font size="4">What happens under the hood to support the Web Forms event model is a little more complex. Look again at the HTML returned by Calc.aspx. Notice that it contains an HTML form and a submit button. Clicking the button posts the form back to the server using an HTTP POST. Recognizing that the POST command represents a postback that occurred because the user clicked the = button, ASP.NET notifies the <span class="programelement">Button</span> object and the <span class="programelement">Button</span> responds by firing a <span class="programelement">Click</span> event on the server. ASP.NET subsequently calls <span class="programelement">OnAdd</span> and then renders the page again into HTML. Because the <span class="programelement">Label</span> control’s <span class="programelement">Text</span> property now has a non-null string assigned to it, this time the HTML output by the <span class="programelement">Label</span> control includes a text string between the &lt;span&gt; and &lt;/span&gt; tags.</font>
						</p>
				</div>
				<div class="cc">
						<div class="title">
								<font size="4">Implementation Notes</font>
						</div>
						<p class="normal">
								<font size="4">Calc.aspx contains no code to prevent the numbers typed into the <span class="programelement">TextBox </span>controls from disappearing following a postback. The &lt;asp:TextBox&gt; tags in Figure 5-6 lack <span class="programelement">Value</span> attributes such as the ones in Figure 5-5’s &lt;input type= “text”&gt; tags. Yet the inputs don’t disappear when you click the = button. Why? Because <span class="programelement">TextBox</span> controls automatically persist their contents across postbacks. Check the HTML returned to the browser following the postback and you’ll find that &lt;input type=“text”&gt; tags rendered by the <span class="programelement">TextBox</span> controls have <span class="programelement">Value</span> attributes that equal the text typed by the user.</font>
						</p>
						<p class="normal">
								<font size="4">To make Calc.aspx as simple as possible, I purposely omitted error checking code. To see what I mean, type something other than a simple integer value (say, “hello”) into one of the text boxes and click the = button. The page you see is ASP.NET’s way of responding to unhandled exceptions. To prevent this error, rewrite Calc.aspx’s <span class="programelement">OnAdd</span> method as follows:</font>
								<br />
								<br />
								<font size="4">void OnAdd (Object sender, EventArgs e)<br />{<br />    try {<br />        int a = Convert.ToInt32 (op1.Text);<br />        int b = Convert.ToInt32 (op2.Text);<br />        Sum.Text = (a + b).ToString ();<br />    }<br />    catch (FormatException) {<br />        Sum.Text = "Error";<br />    }<br />}</font>
								<br />
						</p>
						<p class="continuation">
								<font size="4">This version of <span class="programelement">OnAdd</span> catches the exception thrown when <span class="programelement">Convert.ToInt32</span> is unable to convert the input to an integer and responds by displaying the word “Error” to the right of the push button.</font>
						</p>
				</div>
		</div>
<img src ="http://www.cppblog.com/mzty/aggbug/7212.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/mzty/" target="_blank">梦在天涯</a> 2006-05-15 17:41 <a href="http://www.cppblog.com/mzty/archive/2006/05/15/7212.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>