ASP.NET

HTTP Requests

The communication mechanism by which Web browsers talk to Web sites is named the HyperText Transfer Protocol (HTTP). The World Wide Web as we know it today began as a research project at CERN in Switzerland. In those days, the notion of hypertext-documents linked together arbitrarily-was becoming increasingly popular. Applications such as Hypercard from Apple Computer Inc. introduced hypertext applications to a wider audience. Now, if documents could be linked over a network, that would revolutionize publishing. That's the reason for the HyperText Transfer Protocol, which lies on top of TCP/IP as an application layer.

In its original form, HTTP was meant to transfer hypertext documents. That is, it was originally intended simply to link documents together without consideration for anything like the Web-based user interfaces that are the staple of modern Web sites. The earliest versions of HTTP supported a single GET request to fetch the named resource. It then became the server's job to send the file as a stream of text. After the response arrived at the client's browser, the connection terminated. The earliest versions of HTTP supported only transfer of text streams and did not support any other sort of data transfer.

The first formal specification for HTTP found itself in version 1.0 and was published in the mid-1990s. HTTP 1.0 added support for more complex messaging beyond a simple text transfer protocol. HTTP grew to support different media (specified by the Multipurpose Internet Mail Extensions). The current version of HTTP is version 1.1.

As a connection protocol, HTTP is built around several basic commands. The most important ones we'll see in developing ASP.NET applications are GET, HEAD, and POST.

GET retrieves the information identified by the Uniform Resource Identifier (URI) specified by the request. The HEAD command retrieves only the header information identified by the Uniform Resource Identifier specified by the request (that is, it does not return a message body). You use the POST method to make a request to the server that may cause side effects. You make most initial contacts to a page using a GET command, and you handle subsequent interactions with POST commands.

HTTP Requests from a Browser

As an example, look at the request that is sent from a browser to fetch the helloworld.htm resource from the virtual directory ASPNETStepByStep running on localhost. Listing 1-1 shows the text of the request that is sent to the server. If you would like to see the data going back and forth, there are several TCP monitors available. In addition, you may use TELNET to send GET Requests to the server. Just look for some online. Most are very easy to use.

To send an HTTP request to a server using TELNET, follow these steps:

  1. Open the Visual Studio command prompt to connect to your own PC over port 80.

  2. At the prompt, type the following:

    C:\>TELNET localhost 80
    
  3. After the TELNET client connects, type the following GET command (assuming you have a virtual directory named ASPNETStepByStep on you machine, containing a file named HelloWorld.HTM):

    C:/> GET /ASPNETStepByStep/helloworld.htm
    
  4. You should see the file's contents returned to the command line.

Listing 1-1

GET /ASPNETStepByStep/helloworld.htm HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,
application/vnd.ms-powerpoint, application/vnd.ms-excel,
application/msword, application/x-shockwave-flash, */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR
2.0.50215)
Host: localhost:80
Connection: Keep-Alive

When a browser wants to make an HTTP request, it needs to cook up the HTTP request including the URI along with other information. The header information in the request includes details about the operating environment of the browser and some other information that is often useful to the server. When the server receives this request, it returns the requested resource as a text stream. The browser then parses it and formats the contents. Listing 1-2 shows the response provided by the server when asked for the HelloWorld.htm file. Normally, you don't see all the header information when viewing the resource through a browser. A good TCP tracing utility will show it to you. When we look at ASP.NET's tracing facilities later on, this header information will be visible.

Listing 1-2
HTTP/1.1 200 OK
Server: Microsoft-IIS/5.1
X-Powered-By: ASP.NET
Date: Wed, 01 Jun 2005 23:44:04 GMT
Content-Type: text/html
Accept-Ranges: bytes
Last-Modified: Sun, 22 May 2005 21:54:20 GMT
ETag: "04e9ace185fc51:bb6"
Content-Length: 130
<html>
   <body>
      <h1> Hello World
</h1>
      Nothing really showing here yet, except some HTML...
   </body>
</html>

The first line indicates the protocol and the return code. The rest of the response (until the first <html> tag) is information about the time of the request, the last time the file was modified, and what kind of content is provided. This information will be useful later when we examine such issues as page caching and detecting browser capabilities. The content following the response header information is literally the HTML file sent back by the server.

Making HTTP Requests Without a Browser

In addition to being a framework for building Web applications, the .NET development environment includes classes for making HTTP requests in the raw. The WebRequest class includes a member named GetResponse that will send a request to the address specified by the Uniform Resource Locater. To get a flavor as to how to make direct requests to a Web server without a browser, try compiling and then running this short program that fetches the home page for Microsoft.com.

Build a Simple HTTP Requestor

  1. Start Visual Studio.NET. Select New | Project from the main menu. In the New Project dialog box, select a Console application and name it WebRequestorApp, as shown below.

    Graphic

    Visual Studio will generate a blank Console program for you.

  2. Add the code necessary to make a Web request to the program. Visual Studio places the entry point of the Console application into a file named Program.cs. (This file is the code that shows up in the code window by default.) The code for making a Web request is shown in bold in the following lines of code:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.IO;
    namespace WebRequestorApp
    {
       class Program
       {
          static void Main(string[] args)
          {
          {
             WebRequest req =
                   WebRequest.Create
                      ("http://www.microsoft.com");
             WebResponse resp = req.GetResponse();
             StreamReader reader =
                new StreamReader(resp.GetResponseStream(),
                     Encoding.ASCII);
             Console.WriteLine(reader.ReadToEnd());
         }
      }
    }
    
  3. Run the application. You may do this by choosing Debug | Start Without Debugging from the main menu. Visual Studio will start up a Console for you and run the program. After a couple of moments, you'll see the following HTML spewed to your screen.

Graphic

Of course, the HTML isn't meant for human consumption. That's what a browser is for. However, this example does show the fundamentals of making a Web request-and you can see exactly what comes back in the response.

In this case, the request sent to the server is much smaller. WebRequest.GetResponse doesn't include as much information in the request-just the requisite GET followed by the URI, host information, and connection type:

GET /ASPNETStepByStep/helloworld.htm HTTP/1.1
Host: localhost:80
Connection: Keep-Alive

The fundamental jobs of most browsers are (1) to package a request and send it to the server represented in the URI and (2) to receive the response from the server and render it in a useful way. The response usually comes back as a text stream marked up using HTML tags.