1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft .NET Framework web based client development doc

552 338 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 552
Dung lượng 8,02 MB

Nội dung

PUBLISHED BY Microsoft Press A Division of Microsoft Corporation One Microsoft Way Redmond, Washington 98052-6399 Copyright © 2007 by Glenn Johnson and Tony Northrup All rights reserved No part of the contents of this book may be reproduced or transmitted in any form or by any means without the written permission of the publisher Library of Congress Control Number 2006932076 ISBN-13: 978-0-7356-2334-7 ISBN-10: 0-7356-2334-1 Printed and bound in the United States of America QWT Distributed in Canada by H.B Fenn and Company Ltd A CIP catalogue record for this book is available from the British Library Microsoft Press books are available through booksellers and distributors worldwide For further information about international editions, contact your local Microsoft Corporation office or contact Microsoft Press International directly at fax (425) 936-7329 Visit our Web site at www.microsoft.com/mspress Send comments to tkinput@microsoft.com Microsoft, Active Directory, Internet Explorer, MSDN, MSN, PGR, Segoe, Visual Basic, Visual Studio, Visual Web Developer, Windows, and Windows Server are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries Other product and company names mentioned herein may be the trademarks of their respective owners The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred This book expresses the author’s views and opinions The information contained in this book is provided with- out any express, statutory, or implied warranties Neither the authors, Microsoft Corporation, nor its resellers, or distributors will be held liable for any damages caused or alleged to be caused either directly or indirectly by this book Acquisitions Editor: Ken Jones Project Editor: Jenny Moss Benson Editorial Production: nSight, Inc Copy Editor: Evan Gelder Technical Reviewer: Thomas Keegan Indexer: Nancy Guenther Body Part No X12-48741 About the Authors Glenn Johnson Glenn Johnson is a professional trainer, consultant, and developer whose experience spans the past 20 years As a consultant and developer, he has worked on several large projects, the latest being a successful conversion of a SmallTalk/GemStone system to C#/ Microsoft SQL Server for a very large customer This is Glenn’s third NET-related book, and he has also developed courseware for and taught classes in many countries on Microsoft ASP.NET, Visual Basic NET, C#, and the NET Framework Glenn holds the following Microsoft Certifications: MCT, MCPD, MCTS, MCAD, MCSD, MCDBA, MCP + Site Building, MCSE + Internet, MCP + Internet, and MCSE You can find Glenn’s Web site at http://GJTT.com Tony Northrup Tony Northrup, MCTS, MCSE, CISSP, and Microsoft MVP, is a consultant and author He has written more than a dozen books covering Windows networking, security, and develop ment Among other titles, Tony is coauthor of the MCSA/MCSE Self-Paced Training Kits for Exams 70-536 and 70-330/340 When he’s not consulting or writing, Tony enjoys cycling, hik ing, and nature photography Tony lives in Phillipston, Massa chusetts, with his wife, Erica, his cat, Sam, and his dog, Sandi You can learn more about Tony by visiting his Web site at http://www.northrup.org Chapter Introducing the ASP.NET 2.0 Web Site Microsoft Visual Studio 2005 and ASP.NET 2.0 represent a major release for Microsoft If you have previous experience with Visual Studio products, you will see the differences immediately when you attempt to create your first Web site Even if you are new to Visual Studio 2005 and ASP.NET 2.0, you will be able to immediately take advantage of the productivity enhancements This chapter starts by introducing the Web site players (Web server, Web browser, and Hypertext Transfer Protocol [HTTP]) It explores the architecture of an ASP.NET Web site and then shows the various ways that you can create a Web site After that, you will learn about some of the Web site configuration options in Visual Studio 2005 Exam objectives in this chapter: ■ Program a Web application ❑ Avoid performing unnecessary processing on a round trip by using a page’s IsPostBack property ■ Create and configure a Web application ❑ ❑ ■ Create a new Web application Add Web Forms pages to a Web application Configure settings for a Web application ❑ Configure system-wide settings in the Machine.config file ❑ Configure settings for a Web application in the application’s Web.config file ❑ Manage a Web application’s configuration by using the Web Site Adminis tration Tool ■ Optimize and troubleshoot a Web application ❑ Troubleshoot a Web application by using ASP.NET Trace Chapter Introducing the ASP.NET 2.0 Web Site Lessons in this chapter: ■ Lesson 1: Understanding the Players ■ Lesson 2: Creating a Web Site and Adding New Web Pages 17 ■ Lesson 3: Working with Web Configuration Files 31 ■ Lesson 4: Using ASP.NET Trace to Explore Web Pages 37 Before You Begin To complete this chapter, you must: ■ Be familiar with Microsoft Visual Basic or C# ■ Have Microsoft Windows XP, Internet Information Services (IIS) 5.1, and Visual Studio 2005 installed with Microsoft SQL Server 2005 Express Edition ■ Be familiar with the Visual Studio 2005 Integrated Development Environment (IDE) ■ Understand how to make assemblies available to other applications ■ Have a basic understanding of Hypertext Markup Language (HTML) and client- side scripting Real World Glenn Johnson It’s easier to learn how to develop Web clients once you understand who the players are I have seen many people attempt to learn Web development without learning the roles of the Web browser, HTTP, and the Web server It’s not a pretty sight Lesson 1: Understanding the Players Lesson 1: Understanding the Players It’s important to get an understanding of the roles of the Web server, Web browser, and HTTP before starting your Web development The typical communication pro cess can be generalized into the following steps: The Web browser initiates a request for a Web server resource HTTP is used to send the GET request to the Web server The Web server processes the request The Web server sends a response to the Web browser HTTP protocol is used to send the HTTP response to the Web browser The Web browser processes the response, displaying the Web page The user enters data and performs an action, such as clicking a Submit button that causes the data to be sent back to the Web server HTTP is used to POST the data back to the server The Web server processes the data The Web server sends the response back to the Web browser 10 HTTP is used to send the HTTP response to the Web browser 11 The Web browser processes the response, displaying the Web page This section gives a brief description of how the Web browser exchanges communica tions with the Web server via HTTP It also describes the responsibilities of both the Web browser and Web server After this lesson, you will be able to: ■ Describe the Web server’s role in responding to requests for resources ■ Describe the Web browser’s role in collecting and presenting data to the user ■ Describe HTTP’s role in communicating to the Web server ■ Describe how HTTP verbs are used to request resources from the Web server ■ Describe the status-code groups that are implemented in HTTP ■ Describe Distribute Authoring and Versioning ■ Describe PostBack, the common method of sending data to the Web server ■ Describe some methods for troubleshooting HTTP Estimated lesson time: 30 minutes Chapter Introducing the ASP.NET 2.0 Web Site The Web Server’s Role Let’s start with the Web server The original Web servers were responsible for receiving and handling requests from the browsers via HTTP Each Web server handled the request and sent a response back to the Web browser After that, the Web server closed the connection and released all resources that were involved in the request All resources were released because the Web server needed to be able to handle thou sands of requests per minute, and the original Web pages were simple, static HTML pages The Web environment was considered to be ―stateless‖ because no data was held at the Web server between Web browser requests, and because the connection was closed after the response was sent (see Figure 1-1) Web Browser GET Default.html Web Server Client initiates communications with page request Display Page Server responds with page Process request Send response and close the connection Figure 1-1 A simple request/response between Web browser and Web server in a stateless environment Today’s Web servers deliver services that go far beyond the original Web servers In addition to serving static HTML files, the Web servers can also handle requests for pages that contain code that will execute at the server; the Web servers will respond with the results of code execution, as shown in Figure 1-2 Web servers also have the ability to store data across Web page requests, which means that Web pages can be connected to form Web applications Because many Web sites are set up as Web appli cations containing many Web pages, the idea of a Web server delivering a single page to the Web browser and closing the connection is rather outdated Web servers now implement ―keep alive‖ features for connections that make the Web servers keep the connections to the Web browsers open for a period of time with anticipation of addi tional page requests from a Web browser Lesson 1: Understanding the Players Web Browser GET Default.aspx Web Server Client initiates communications with page request Process request Execute server-side code Store session data e.g., CustomerId=5234 Display Page Send result response Server responds with page Figure 1-2 Web servers now store state between page requests to enable the creation of Web applications The Web Browser’s Role The Web browser provides a platform-independent means of displaying Web pages that were written with HTML Platform-independent means that HTML was designed to be able to render within any operating system while placing no constraint on the window size HTML was designed to ―flow,‖ wrapping text as necessary to fit into the browser window The Web browser also needs to display images and respond to hyperlinks Each Web page request to the Web server results in the Web browser clearing the browser screen and displaying the new Web page Although the Web browser’s role is simply to present data and collect data, many new client-side technologies enable today’s Web browsers to execute code such as JavaScript and to support plug-ins which improve the user’s experience Technologies such as Asynchronous JavaScript and XML (AJAX) allow the Web browsers to talk to the Web servers without clearing the existing Web pages from the browser window These technologies make the user experience much better and more robust than the user experience provided by the original Web browsers Understanding Hypertext Transfer Protocol’s Role HTTP is a text-based communication protocol that is used to request Web pages from the Web server and send responses back to the Web browser HTTP messages are Chapter Introducing the ASP.NET 2.0 Web Site typically sent between the Web server and Web browser using port 80, or, when using secure HTTP (HTTPS), port 443 MORE INFO HTTP/1.1 Specification For more information on HTTP/1.1, see the HTTP/1.1 specification at http://www.w3.org/Protocols/ rfc2616/rfc2616.html When a Web page is requested, a textual command like the following is sent to the Web server: GET /default.aspx HTTP/1.1 Host: www.northwindtraders.com Notice that the first line contains the method, also known as a verb or a command, called GET, and is followed by the Uniform Resource Locator (URL) of the Web page to be retrieved, which is followed by an indicator of the HTTP version to be used The method indicates what action is to be performed by the Web server using the URL that follows the method Table 1-1 contains a list of some of the common HTTP meth ods with a description of their uses Note that, if Distributed Authoring and Versioning (DAV) is enabled on the Web site, many more verbs will be available, such as LOCK and UNLOCK The second line identifies the name of the host that may be used by the Web server if the Web server is hosting more than one Web site This process is known as using host headers to identify the Web site that will handle the request(s) Table 1-1 Common HTTP/1.1 Methods HTTP Method Description OPTIONS Used by client applications to request a lists of all supported verbs Checks to see if a server allows a particular verb before wasting net work bandwidth trying to send an unsupported request GET Gets a URL from the server A GET request for a specific URL, say, /test.htm, retrieves the test.htm file Data retrieved using this verb is typically cached by the browser GET also works with collections, such as those in directories that contain collections of files If you request a directory, the server can be configured to return a default file, such as index.html, that may be representative of the directory Lesson 1: Understanding the Players Table 1-1 Common HTTP/1.1 Methods HTTP Method Description HEAD Retrieves the meta information for a resource This information is typ ically identical to the meta information sent in response to a GET request, but the HEAD verb never returns the actual resource The meta information is cacheable POST Used to create a new, dynamically named resource Data retrieved using this verb is typically not cached PUT Allows a client to directly create a resource at the indicated URL on the server The server takes the body of the request, creates the file specified in the URL, and copies the received data to the newly cre ated file If the file exists and is not locked, the content of the file will be overwritten DELETE Used to delete a resource at the Web server Requires write permis sions on the directory TRACE Used for testing or diagnostics; allows the client to see what is being received at the other end of the request chain Responses to this method are never cached CONNECT Reserved for use with a proxy that can dynamically switch to being a tunnel, such as Secure Socket Layer (SSL) protocol DEBUG Is not defined in the HTTP/1.1 specification, but is used to start ASP.NET debugging Informs Visual Studio 2005 of the process that the debugger will attach to Notice that Web-browser-to-Web-server communication is referred to as a request In ASP.NET, the Request object represents the Web browser’s communications to the Web server asking for a resource What Is Distributed Authoring and Versioning? Distributed Authoring and Versioning (DAV) is a set of extensions to HTTP/1.1 that simplifies Web site development when working in a team scenario DAV is an open standard and is available on numerous platforms DAV provides the ability to lock and unlock files plus the ability to designate versions Lesson 2: Using Windows, Forms, Passport, and Anonymous Authentication 703 Web site, allowing the ASP.NET application to validate requests This cookie can, option ally, be encrypted by a private key located on the Web server, enabling the Web server to detect an attacker who attempts to present a cookie that the Web server did not generate ASP.NET membership allows you to quickly add forms authentication to your Web application Because Microsoft thoroughly tests the controls and classes involved in authentication and storing the user information, these controls are probably more secure than controls that any developer might make Therefore, you should use ASP.NET membership whenever possible However, if you need complete control over how users are authenticated and man aged, you can also create custom forms authentication controls and pages In the sec tions that follow, you will learn how to configure an ASP.NET configuration file to require forms authentication, how to add user credentials to a Web.config file, and how to create an ASP.NET Web form to authenticate users Configuring a Web.Config File for Forms Authentication To configure forms authentication, you have to create an authentication page that uses an HTML form to prompt the user for credentials Therefore, forms authentication can be used on only those ASP.NET Web applications developed with this authenti cation method in mind Although you can choose to rely on administrators to config ure Windows or on anonymous authentication, you must distribute a Web.config file for your application to use forms authentication Administrators deploying your application should not need to modify the Web.config file, but they can control some aspects of how Forms authentication behaves, such as configuring the timeout period after which a user will need to log on again A simple Web.config file requiring Forms authentication is shown here: In the preceding example, all users who have not yet signed in are redirected to the LoginForm.aspx page when they attempt to access any ASP.NET file Typically, the 704 Chapter 11 Implementing Authentication and Authorization form prompts the user for a user name and password and handles authentication within the application itself Regardless of the way the application handles the user’s input, the user’s credentials are sent to the server as a Hypertext Transfer Protocol (HTTP) request—without any automatic encryption HTTP is the protocol Web browsers and Web servers use to communicate The best way to ensure privacy of user credentials submitted by using forms authentication is to configure an Secure Sockets Layer (SSL) certificate within IIS and require Hypertext Transfer Protocol Secure (HTTPS) for the login form HTTPS is an encrypted form of the HTTP protocol, which is used by virtually every e-commerce Web site on the Internet to protect private information about end users and to protect end users from submitting private information to a rogue server impersonating another server The user name and password can be checked against a database, a list contained in the Web.config file, an Extensible Markup Language (XML) file, or any other mecha nism you create Forms authentication is tremendously flexible; however, you are entirely responsible for protecting your authentication mechanism from attackers Because proof of authentication is stored in a cookie provided by the Web server (by default), and that cookie generally contains only the user’s user name, an attacker can potentially create a fake cookie to trick the Web server into considering the user as authenticated ASP.NET includes the ability to encrypt and validate authentication cookies, but naturally, this protection includes some overhead for the Web server The type of encryption and validation used is controlled by the protection attribute of the section If the protection attribute is not set, it defaults to All If the protection attribute is set to Encryption, the cookie is encrypted with 3DES This encryption protects the privacy of the data contained in the cookie but performs no validation If the protection attribute is set to Validation, as the following example demonstrates, the server verifies the data in the cookie upon each transaction to reduce the likelihood of it being modified between the time it is sent from the browser and the time it is received by the server If the protection attribute is set to None, nei ther encryption nor validation is performed This setting reduces the overhead on the server, but it is suitable only in situations where privacy is not a concern, such as Web site personalization Note its usage here: Lesson 2: Using Windows, Forms, Passport, and Anonymous Authentication IMPORTANT Optimizing security for forms authentication For optimal security (with a slight performance cost), leave protection at the default setting of All By default, ASP.NET stores the authentication token in a cookie for most devices However, if the browser does not support cookies, ASP.NET will store the authentica tion information as part of the URL You can control this behavior by setting the cook ieless attribute of the element to one of the following settings: ■ UseCookies Always attempts to send a cookie to the client, even if the client indi cates it cannot support cookies ■ Always stores the authentication token as part of the URL rather than a cookie Technically, the token is stored in the Uniform Resource Identifier (URI), UseUri which is the last portion of the URL If a browser indicates that it supports cookies, the AutoDetect set ting causes ASP.NET to test whether the browser actually does support cookies If it does not, or if the browser indicates that it does not support cookies, ■ AutoDetect ■ ASP.NET uses cookieless authentication instead UseDeviceProfile The default setting, UseDeviceProfile, uses a cookie to prove authentication if the browser profile indicates that it supports cookies You might find that some users have changed the default setting to not allow cookies In this case, forms authentication does not work properly unless you change this setting to AutoDetect For example, the following section of a Web.config file enables cookieless forms authentication for all clients This works well, but it causes the authentication token to be included in bookmarks and whenever the user sends a URL to another user: Another important attribute of the section is timeout, which defines, in minutes, the amount of idle time allowed between requests before the user is forced to log on again If the section is , the user is forced to log on again if he or she does not send any requests to the ASP.NET application within 10 minutes This number should be decreased to reduce the risk of 705 706 Chapter 11 Implementing Authentication and Authorization the browser being misused while the user is away from the computer The sec tion has other attributes, but LoginUrl, protection, and timeout are the most important Quick Check By default, under what circumstances does forms authentication provide cookies to the browser? If you have users who have disabled cookies in their browsers, what can you to enable them to use forms authentication? Quick Check Answers By default, cookies are provided to browser types that support cookies, whether or not the browser has cookies enabled Use the AutoDetect setting Configuring User Accounts in the Web.Config File To avoid creating a database to store user credentials, you can store the user creden tials directly in the Web.config file The passwords can be stored in one of three for mats: clear text, encrypted with the MD5 one-way hash algorithm, or encrypted with the SHA1 one-way hash algorithm Using one of the two hash algorithms to mask the user credentials reduces the likelihood that a malicious user with read access to the Web.config file will gather another user’s login information Define the hashing method used within the section, in the section An example is shown here:

Ngày đăng: 15/03/2014, 05:20

TỪ KHÓA LIÊN QUAN