Vous êtes sur la page 1sur 7

CHAPTER1

Introducing ASP.NET 4
Lesson 1: Understanding Web Communications
Like all client-server applications, web applications have two distinct components:
■ Client Also known as the front-end interface, the web browser presents the user interface, accepts user
input, and sends data to the server for processing.
■ Server Also known as the back end, the web server responds to requests from clients for specific pages.
It responds with an HTML page that includes instructions for how to generate the user interface.
The web browser (the client) and the web server communicate by using Hypertext Transfer
Protocol (HTTP), a text-based network protocol assigned to TCP port 80. If the server has a certificate, the
client and server can use HTTP Secure (HTTPS) to authenticate the server and encrypt communications.
HTTPS is assigned to TCP port 443.
The web server uses HTTP to send a response back to the web browser. If the request was
processed successfully, the web server returns the HTTP status code 200, along with an HTML document.
If the server cannot find the page, it returns the code 404. If the user requests an outdated or relocated
page, the server returns the code 302 and the new URL so that the browser can access the correct page.
This is known as redirection. Several other responses are possible as well, depending on the particular
situation.

The Web Server’s Role


When a web server receives a request, some of the actions it takes are to:
1. Verify that the request is structured legitimately. Sometimes, malicious clients send malformed
web requests to compromise web servers. Web servers must be able to detect this and respond
appropriately—usually by ignoring the request.
2. Authenticate itself. If the server has a Secure Sockets Layer (SSL) certificate and the request was
made with HTTPS, the web browser uses the certificate to authenticate the server. The web server will
also encrypt all content before returning it to the web browser.
3. Authenticate the user. If the content requires authorization, the web server verifies that the user has
submitted credentials. If the user has not been authenticated, the web server redirects the user to an
authentication form.
4. Authorize the user. After the Web server authenticates the user, the web server verifies that the user
is allowed to access the requested content.
5. Determine how to handle a request. If the web browser requested static content or was simply
determining whether cached content could still be used, the web server can directly respond. If the web
browser requested an ASP.NET page, the web server must forward the request to ASP.NET.
6. Handle errors. If a server cannot process the user’s request, it provides error information to the web
browser.
7. Cache output. Web servers can cache output to improve the response time of subsequent requests.
Web servers also provide caching information to web browsers, so browsers know how long to keep
content cached.
8. Compress output. Before returning a page to a web browser, a web server can compress the content
to reduce the bandwidth required.
9. Log access. Web servers typically record usage information for security and performance-monitoring
purposes.

The Web Browser’s Role


1. Send requests to the web server. If the user enters http://www.microsoft.com, the web browser
resolves the www.microsoft.com Domain Name System (DNS) address, uses HTTP to connect to the
server, and requests a page.
2. Authenticate the server. If the server has an SSL certificate and the request was made with HTTPS,
the web browser uses the certificate to authenticate the server and then decrypt future communications.
3. Process the response. If the server has provided HTML, the browser retrieves embedded objects,
such as images, videos, or animations referenced in the HTML. If the server has provided an error,
redirection, or other response, the browser responds appropriately.
4. Display HTML and embedded objects. Web browsers use HTML standards to determine how to
display a webpage to the user. Because HTML can contain embedded objects, a web browser might have
to display dozens of objects to render a single webpage.
5. Run client scripts. Client scripts, such as those written in JavaScript, enable interactive and
responsive pages without reloading the page.

Understanding the Role of HTTP


HTTP is a text-based communication protocol that is used to request webpages from a web server and
send responses back to a web browser. The request might look like the following.
GET /default.aspx HTTP/1.1
Host: www.northwindtraders.com
The first words, known as the method GET. Uniform Resource Identifier (URI) the URI is /default.aspx.
Following the URI is the version of HTTP to be used to process the command. The HTTP version is
HTTP/1.1.
The second line of the request (Host: www.northwindtraders.com) identifies the name of the
website. Most web servers host multiple websites with a single IP address, and need to know the website’s
name to return the correct page. This process involves using host headers to identify the website that will
handle the request.
If a website has Distributed Authoring and Versioning (DAV) enabled, many more commands are
available, including LOCK and UNLOCK.

What Is Distributed Authoring and Versioning?


Distributed Authoring and Versioning (DAV) is a set of extensions to HTTP/1.1 that simplifies website
development when work is being carried out in a team scenario. DAV is an open standard and is available on
numerous platforms. DAV provides the ability to lock and unlock files and the ability to designate versions. DAV
is built directly on HTTP/1.1, so no other protocols, such as File Transfer Protocol (FTP) or Server Message Block
(SMB), are required. DAV also provides the ability to query the web server for various resource properties such
as file names, time stamps, and sizes. DAV also gives developers the ability to perform server-side file copying
and moving. For example, you can use the HTTP GET and PUT commands to retrieve files from the web servers
and save them to different locations, or you can use DAV’s COPY command to tell a server to copy a file.
In ASP.NET, there is a Request object that is used to represent the web browser’s communications
to the web server. ASP.NET wraps the resource request in an object that can be queried in code. By
wrapping the HTTP request in a programmable object, ASP.NET provides your code access to things such
as the cookies associated with your site, the query string parameters passed with the URL and the path to
the requested resource, and allows you to work with other relevant request-based information.
The communication from the web server back to the web browser is wrapped in the Response
object. You can use this object to set cookies, define caching, set page expiration, and more. When a web
server responds to a request, it uses what it finds in the Response object to write the actual, text-based
HTTP response, such as the following.
HTTP/1.1 200 OK
Server: Microsoft-IIS/6.0
Content-Type: text/html
Content-Length: 38
<html><body>Hello, world.</body></html>
The first line indicates the communication protocol and version information. It also includes the status
code for the response and the reason that describes the status code.

The second line of the response indicates the type of web server (Server: Microsoft-IIS/6.0). The
third line (Content-Type) indicates the type of resource that is being sent to the web browser as part of
the response. This indicator is in the form of a Multipurpose Internet Mail Extensions (MIME) type. In this
example (Content-Type: text/html), the file is an HTML text file. The MIME type is a two-part designator
that is shown as type/subtype, in which the first part is the resource type (text, in this example) and the
second part is the resource subtype (html, in this example).
The next line is content length (Content-Length: 38 in this example). This simply indicates the size
of the content (in “octets,” or 8-bit bytes) that follows. After the Content-Length line, the response
message is returned. The browser attempts to process the content based on its MIME type. For example,
it interprets HTML for HTML MIME types and shows a picture for image MIME types.

Submitting Form Data to the Web Server


The HTML <form> tag can be used to create a webpage that collects data from the user and sends the
collected data back to the web server. The form tag is nested inside the <HTML> tags. The form tags
typically include information for the user in the form of text, and input tags for defining controls such as
buttons and text boxes.

<form method="POST" action="getCustomer.aspx">


Enter Customer ID:
<input type="text" name="Id">
<input type="submit" value="Get Customer">
</form>

The method attribute of the form tag indicates the HTTP command (POST) to use when sending the
request to the server. The action attribute is the relative URL of the page to which the request will be
sent.
There are two HTTP commands that can be used to submit the form data to the web server: GET
and POST. When the GET command is used, the form data is appended to the URL as part of the query
string. The query string is a collection of key–value pairs, separated by an ampersand (&) character. The
start of the query string is indicated by a question mark (?). The following provides an example.
GET /getCustomer.aspx?Id=123&color=blue
HTTP/1.1
Host: www.northwindtraders.com
In this example, a GET request is made to the web server for a webpage called getCustomer.aspx
on the root of the website (indicated by the forward slash). The query string contains the form data
following the question mark (?).
When the GET command is used to send data to the server, the complete URL and query string can be
seen and modified in the address bar of the web browser.
However, it’s not a good choice for authentication pages, because the user’s credentials would be
visible in the URL. It’s also not a good choice when the user needs to transfer large amounts of
information, because when Windows Internet Explorer and Internet Information Services (IIS) are used,
the limit for a query string is 1,024 characters (other browsers and server implementations also have
limitations, although they might not limit the length to the values IIS and Internet Explorer use).
The POST command is a better choice for submitting credentials and large amounts of data. When
the POST command is used, the data is placed into the message body of the request as follows.
POST /getCustomer.aspx HTTP/1.1
Host: www.northwindtraders.com
Id=123&color=blue
Using the POST command removes the input from the URL and overcomes size constraints.
Instead, the data is hidden in the message body.
Sending data back to the server as part of your request is often referred to as a postback in ASP.NET.
Although its name comes from the POST command, it is possible to perform a postback by using the GET
command already described. An ASP.NET webpage contains a property called IsPostBack that is used to
determine if data is being sent back to the web server or if the webpage is simply being requested.

Quick Check
1. What protocol is used to communicate between the web browser and the web server?
2. In ASP.NET, what does the Request object represent?
3. In ASP.NET, what does the Response object represent?
Quick Check Answers
1. HTTP is used for web browser and web server communication.
2. The Request object in ASP.NET wraps the communication from the web browser to the web server.
3. The Response object in ASP.NET wraps the communication from the web server to the web browser.

Lesson Summary
■ The web server is responsible for accepting requests for a resource and sending the appropriate
response.
■ The web browser is responsible for displaying data to the user, collecting data from the user, and
sending data to the web server.
■ HTTP is a text-based communication protocol that is used to communicate between web browsers and
web servers by using TCP port 80 by default.
■ Secure HTTP (HTTPS) uses TCP port 443 by default.
■ Each HTTP method indicates the desired action. The most common methods are GET and POST.
■ The process of sending data to a web server from a browser is commonly referred to as a postback in
ASP.NET programming.
■ You can troubleshoot HTTP by using a sniffer such as Microsoft Network Monitor.
Lesson Review
1. From within an ASP.NET page, you need to run a section of code only if the user has previously loaded the page
and is submitting data as part of a form. Which Page object property should you use?
A. IsCallback
B. IsReusable
C. IsValid
D. IsPostBack
Answer: D
A. Incorrect: IsCallback is generated by client-side scripts and does not involve reloading a page.
B. Incorrect: IsReusable is a standard property that indicates whether an object can be reused.
C. Incorrect: IsValid indicates whether page validation succeeded. IsValid is discussed in more detail in Chapter 5,
“Input Validation and Site Navigation.”
D. Correct: If IsPostBack is true, the page loading is the result of a form being submitted by the user. IsPostBack is
discussed in more detail in Chapter 5.

2. You are troubleshooting a problem users have when submitting information with a form. The form data does not
appear in the web browser’s address bar, but you know the web server is receiving the form data. After capturing the
web communications with a sniffer, which type of HTTP request should you examine to see the data the user
submitted?
A. PUT
B. CONNECT
C. POST
D. GET
Answer: C
A. Incorrect: The PUT command is used to add a file to a web server.
B. Incorrect: The CONNECT command is not frequently used. It is reserved for use with proxy servers under very
specific conditions.
C. Correct: The POST command is used when a browser submits the results of a form. The form data is stored as part
of the response packet.
D. Incorrect: The GET command is used to submit a form with the form data included as part of the URI.

Lesson 2: Creating a Website and Adding New Webpages


Creating Websites
You can create a web project connected to a file-system–based server on your computer, an IIS server, or
an FTP server. The option that is right for your website project depends on how you want to run, share,
manage, and deploy your project.
■ File system A file-system–based website stores all of the files for the website inside a directory of your
choosing. When you debug the website, Visual Studio runs the lightweight ASP.NET development server
that is included in Visual Studio. A file-system–based site is great when you want to run and debug your
website locally but do not want to run a local IIS web server (or cannot due to security restrictions on your
network).
■ FTP An FTP-based website is useful when you want to connect to your site via FTP to manage your files
on a remote server. This option is typically used when your website is hosted on a remote computer and
your access to the files and folders on that server is through FTP.
■ HTTP An HTTP-based website is used when you are working with a site deployed inside of IIS (either
locally or on a remote server).
This type of website might be configured at the root of the IIS web server or in a virtual directory
that is configured as an application. Note that a remote server running IIS will need the WebDAV
Publishing role service or Microsoft Front Page Server Extensions 2002.

Creating a Website Project


Create new website project directly from Visual Studio.
1. In Visual Studio, use the File menu to create a new website (File | New | Web Site).
2. Select the website type, location, Microsoft .NET Framework version, and default programming
language.
You can also use Visual Studio to create an ASP.NET web application or ASP.NET Empty Web Application.

Web applications and websites function and perform similarly, but web applications differ from websites in
several important ways. For example, with a web application:
■ You can create an MVC application.
■ Visual Studio stores the list of files in a project file (.csproj or .vbproj), rather than relying on the folder
structure.
■ You cannot mix Visual Basic and C#.
■ You cannot edit code without stopping a debugging session.
■ You can establish dependencies between multiple web projects.
■ You must compile the application before deployment, which prevents you from testing a page if another
page will not compile.
■ You do not have to store the source code on the server.
■ You can control the assembly name and version.
■ You cannot edit individual files after deployment without recompiling.
Typically, website projects are the right choice when one developer will be creating and managing a
website. Web application projects are better for enterprise environments with multiple developers and
formal processes for testing, deployment, and administration.

Creating a File-System–Based Website


A file-system–based website runs locally on the ASP.NET web server that ships with Visual Studio. This
option allows you to keep your development local until you are ready to publish code to a server for
sharing. To create a file-system–based website, you use the New Web Site dialog box and select File
System from the Web Location list box. You then simply set a valid folder location for storing your website
files locally on a hard drive.
Visual Studio creates the folder for your site and adds two content webpages (Default.aspx and
About.aspx), their code-behind files, and a master file named Site.master, with a code behind file. The
default website template also creates the folder App_Data, as well as a configuration file called
Web.config.

Creating a File -System –Based Website on a Server


For learning and testing purposes, you should create websites on your local computer. However, in a
production environment, you might need to create and update websites stored on remote servers, such
as servers running Windows Server 2008 R2 and IIS 7.5.
IIS 7.5 does not support Front Page Server Extensions because it uses WebDAV natively. Therefore,
you cannot use HTTP to create the website. However, you can create a file-system– based or FTP website.
Of those two, the file-system–based website is preferred.
To create a file-system–based website on a remote server running Windows Server 2008 R2, follow
these high-level steps on the server:
1. Install .NET Framework 4 on the server (if it has not yet been installed).
2. Install IIS 7.5 with the ASP.NET role service.
3. After IIS is installed, open the IIS Manager. In the IIS Manager, create a new website that uses the
ASP.NET 4 application pool.
4. Grant web developer user accounts NTFS Write permissions for the website folder.
5. From Windows Explorer, share the website folder. Grant web developer user accounts Change share
permissions.
Then, on your development computer, follow these steps:
1. Use Windows Explorer to map a network drive to the shared folder.
2. Use Visual Studio to create a file-system–based website by specifying the drive letter of the WebDAV
network drive.
When you debug or start without debugging from Visual Studio, it will run the website by using the
lightweight ASP.NET development server that is included in Visual Studio. However, you can open the
remote server’s website by using Internet Explorer or another web browser, to verify that the site
functions correctly on the website.

Creating a File -System –Based Website with Web DAV


The easiest way to publish a website to a server is to map a drive to the server. If firewall restrictions
prevent you from mapping a drive, you can publish the website across HTTP by using WebDAV. On a
server running Windows Server 2008 R2, follow the steps in the previous section to configure IIS, but do
not share the folder by using Windows Explorer. Instead, configure WebDAV by following these high-level
steps:
1. Add the WebDAV Publishing role service to IIS.
2. In the IIS Manager, add a WebDAV Authoring Rule to grant your user account access to Read, Write,
and Source for the new website.
3. Enable WebDAV on the server.
4. On your client computer, map a network drive to the website’s URL. You can do this from a command
prompt by running the following command.
net use * http://<website_url>
5. On your client computer, use Visual Studio to create a file-system–based website by specifying the
drive letter of the WebDAV network drive.