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

Pro ASP.NET MVC Framework phần 5 pot

50 546 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 50
Dung lượng 16,32 MB

Nội dung

■Note As you’ll learn in Chapter 14, you deploy an MVC application by copying much of this folder struc- ture to your web server. For security reasons, IIS won’t serve files whose full paths contain web.config, bin, App_code, App_GlobalResources, App_LocalResources, App_WebReferences, App_Data,or App_Browsers, because IIS 7’s applicationHost.config file contains <hiddenSegments> nodes hiding them. (IIS 6 won’t serve them either, because it has an ISAPI extension called aspnet_filter.dll that is hard-coded to filter them out.) Similarly, IIS is configured to filter out requests for *.asax, *.ascx, *.sitemap, *.resx, *.mdb, *.mdf, *.ldf, *.csproj, and various others. Those are the files you get by default when creating a new ASP.NET MVC web application, but there are also other folders and files that, if they exist, can have special meanings to the core ASP.NET platform. These are described in Table 7-2. Table 7-2. Optional Files and Folders That Have Special Meanings Folder or File Meaning /App_GlobalResources Contain resource files used for localizing WebForms pages. You’ll /App_LocalResources learn more about localization in Chapter 15. /App_Browsers Contains .browser XML files that describe how to identify specific web browsers, and what such browsers are capable of (e.g., whether they support Jav aScr ipt). /App_Themes Contains WebForms “themes” (including .skin files) that influence how WebForms controls are rendered. These last few are really part of the core ASP.NET platform, and aren’t necessarily so rele- vant for ASP.NET MVC applications. For more information about these, consult a dedicated ASP.NET platform reference. Naming Conventions As you will have noticed by now, ASP.NET MVC prefers convention over configuration. 1 This means, for example, that you don’t have to configure explicit associations between controllers and their views; you simply follow a certain naming convention and it just works. (To be fair, there’s still a lot of configuration you’ll end up doing in web.config, but that has more to do with IIS and the core ASP.NET platform.) Even though the naming conventions have been mentioned previously, let’s clarify by recapping: • C ontroller classes must have names ending with Controller (e.g., ProductsController). This is har d-coded into DefaultControllerFactory: if y ou don ’ t follo w the convention, it won’t recognize your class as being a controller, and won’t route any requests to it. Note that if y ou create your own IControllerFactory (descr ibed in Chapter 9), you don’t have to follow this convention. CHAPTER 7 ■ OVERVIEW OF ASP.NET MVC PROJECTS 207 1. This tactic (and this phrase) is one of the original famous selling points of Ruby on Rails. 10078ch07.qxd 3/26/09 12:24 PM Page 207 • View templates (*.aspx, *.ascx), should go into the folder /Views/controllername. Don’t include the trailing string Controller here—views for ProductsController should go into /Views/Products (not /Views/ProductsController). • The default view for an action method should be named after the action method. For e xample, the default view for P roductsController ’ s L ist a ction would go at / Views/ Products/List.aspx . Alternatively, you can specify a view name (e.g., by returning View("SomeView")), and then the framework will look for /Views/Product/SomeView.aspx. • When the framework can’t find a view called /Views/Products/Xyz.aspx, it will try /Views/Products/Xyz.ascx. If that fails, it tries /Views/Shared/Xyz.aspx and then /Views/Shared/Xyz.ascx. So, you can use /Views/Shared for any views that are shared across multiple controllers. All of the conventions having to do with view folders and names can be overridden using a custom view engine. You’ll see how to do this in Chapter 10. The Initial Application Skeleton As you can see from Figure 7-1, newborn ASP.NET MVC projects don’t enter the world empty handed. Already built in are controllers called HomeController and AccountController, plus a few associated view templates. Quite a bit of application behavior is already embedded in these files: • HomeController can render a Home page and an About page. These pages are generated using a master page and a soothing blue-themed CSS file. • AccountController allows visitors to register and log on. This uses Forms Authentica- tion with cookies to keep track of whether each visitor is logged in, and it uses the core ASP.NET membership facility to record the list of registered users. The membership facility will try to create a SQL Server Express file-based database on the fly in your /App_Data folder the first time anyone tries to register or log in. This will fail if you don’t have SQL Server Express installed and running. • AccountController also has actions and views that let registered users change their passwords. Again, this uses the ASP.NET membership facility. The initial application skeleton provides a nice introduction to how ASP.NET MVC appli- cations fit together , and helps people giving demonstrations of the MVC Framework to have something moderately interesting to show as soon as they create a new project. However, it’s unlikely that you’ll want to keep the default behaviors unless your applica- tion r eally does use the cor e ASP.NET membership facility (covered in much more detail in Chapter 15) to record registered users. You might find that you start most new ASP.NET MVC pr ojects b y deleting many of these files, as w e did in Chapters 2 and 4. Debugging MVC Applications and Unit Tests You can debug an ASP .NET MVC application in exactly the same way you’d debug a traditional ASP.NET WebForms application. Visual Studio 2008’s debugger is essentially the same as its pre- vious incarnations, so if you are already comfortable using it, you can skip over this section. CHAPTER 7 ■ OVERVIEW OF ASP.NET MVC PROJECTS208 10078ch07.qxd 3/26/09 12:24 PM Page 208 Launching the Visual Studio Debugger The easiest way to get a debugger going is simply to press F5 in Visual Studio (or go to Debug ➤ S tart Debugging). The first time you do this, you’ll be prompted to enable debugging in the Web.config file, as shown in Figure 7-2. Figure 7-2. Visual Studio’s prompt to enable debugging of WebForms pages When you select “Modify the Web.config file to enable debugging,” Visual Studio will update the <compilation> node of your Web.config file: <system.web> <compilation debug="true"> </compilation> </system.web> This means that your ASPX and ASCX templates will be compiled with debugging sym- bols enabled. It doesn’t actually affect your ability to debug controller and action code, but Visual Studio insists on doing it anyway. There’s a separate setting that affects compilation of your .cs files (e.g., controller and action code) in the Visual Studio GUI itself. This is shown in Figure 7-3. Make sure it’s set to Debug (Visual Studio won’t prompt you about it). Figure 7-3. To use the debugger, make sure the project is set to compile in Debug mode. ■Note When deplo ying to a production web server, you should only deploy code compiled in Release mode. Similarly , you should set <compilation debug="false"> in your production site’ s Web.config file, too. You’ll learn about the reasons for this in Cha pter 14. CHAPTER 7 ■ OVERVIEW OF ASP.NET MVC PROJECTS 209 10078ch07.qxd 3/26/09 12:24 PM Page 209 Visual Studio will then launch your application with the debugger connected to its built- i n development web server, W ebDev.WebServer.exe . All you need to do now is set a breakpoint, as described shortly (in the “Using the Debugger” section). Attaching the Debugger to IIS If, instead of using Visual Studio’s built-in web server, you’ve got your application running in IIS on your development PC, you can attach the debugger to IIS. In Visual Studio, press Ctrl+Alt+P (or go to Debug ➤ “Attach to Process”), and find the worker process named w3wp.exe (for IIS 6 or 7) or aspnet_wp.exe (for IIS 5 or 5.1). This screen is shown in Figure 7-4. ■Note If you can’t find the worker process, perhaps because you’re running IIS 7 or working through a Remote Desktop connection, you’ll need to check the box labeled “Show processes in all sessions.” Also make sure that the worker process is really running by opening your application in a web browser (and then click Refresh back in Visual Studio). On Windows Vista with UAC enabled, you’ll need to run Visual Studio in elevated mode (it will prompt you about this when you click Attach). Figure 7-4. Attaching the Visual Studio debugger to the IIS 6/7 worker process Once you’ve selected the IIS process, click Attach. Attaching the Debugger to a Test Runner (e.g., NUnit GUI) I f you do a lot of unit testing, you’ll find that you run your code through a test runner, such as NUnit GUI, just as much as you r un it thr ough a w eb server. When a test is inexplicably failing (or inexplicably passing), you can attach the debugger to your test runner in exactly the same way that y ou’d attach it to IIS. Again, make sure your code is compiled in Debug mode, and then use the A ttach to P r ocess dialog (Ctrl+Alt+P), finding y our test runner in the Available Processes list (see Figure 7-5). CHAPTER 7 ■ OVERVIEW OF ASP.NET MVC PROJECTS210 10078ch07.qxd 3/26/09 12:24 PM Page 210 Figure 7-5. Attaching the Visual Studio debugger to NUnit GUI Notice the Type column showing which processes are running managed code (i.e., .NET code). You can use this as a quick way to identify which process is hosting your code. Remote Debugging If you have IIS on other PCs or servers in your Windows domain, and have the relevant debug- ging permissions set up, you can enter a computer name or IP address in the Qualifier box and debug remotely. If you don’t have a Windows domain, you can change the Transport drop- down to Remote, and then debug across the network (having configured Remote Debugging Monitor on the target machine to allow it). Using the Debugger Once Visual Studio’s debugger is attached to a process, you’ll want to interrupt the application’s execution so you can see what it’s doing. So, mark some line of your source code as a break- point by right-clicking a line and choosing Breakpoint ➤ “Insert breakpoint” (or press F9, or click in the gray area to the left of the line). You’ll see a red circle appear. When the attached process reaches that line of code, the debugger will halt execution, as shown in Figure 7-6. Figure 7-6. The debugger hitting a breakpoint CHAPTER 7 ■ OVERVIEW OF ASP.NET MVC PROJECTS 211 10078ch07.qxd 3/26/09 12:24 PM Page 211 The Visual Studio debugger is a powerful tool: you can read and modify the values in vari- a bles (by hovering over them or by using the Watch window), manipulate program flow (by dragging the yellow arrow), or execute arbitrary code (by entering it into the Immediate win- dow). You can also read the call stack, the machine code disassembly, the thread list, and other information (by enabling the relevant item in Debug ➤ Windows). A full guide to the debugger is off-topic for this book; however, consult a dedicated Visual Studio resource for more information. Stepping into the .NET Framework Source Code There’s one little-known debugger feature that, in 2008, suddenly became a lot more useful. If your application calls code in a third-party assembly, you wouldn’t normally be able to step into that assembly’s source code during debugging (because you don’t have its source code). However, if the third party chooses to publish the source code through a symbol server, you can configure Visual Studio to fetch that source code on the fly and step into it during debugging. Since January 2008, Microsoft has enabled a public symbol server containing source code for most of the .NET Framework libraries. This means you can step into the source code for System.Web.dll and various other core assemblies, which is extremely useful when you have an obscure problem and not even Google can help. This contains more information than the disassembly you might get from Reflector—you get the original source code, with comments (see Figure 7-7). To set this up, make sure you have Visual Studio 2008 SP1 installed, and then follow the instructions at referencesource.microsoft.com/serversetup.aspx. Figure 7-7. Stepping into Microsoft’s source code for ASP.NET Forms Authentication CHAPTER 7 ■ OVERVIEW OF ASP.NET MVC PROJECTS212 10078ch07.qxd 3/26/09 12:24 PM Page 212 ■Note Microsoft has made the ASP.NET MVC Framework’s source code available to download so that you can compile it (and modify it) yourself. However, it has not released the source code to the rest of the .NET Frame- work libraries in the same way—you can only get that though Microsoft’s symbol server for the purposes of stepping into it while debugging. You can’t download the whole thing, and you can’t modify or compile it yourself. Stepping into the ASP.NET MVC Source Code Since you can download the whole ASP.NET MVC Framework source code package, it’s possi- ble to include the System.Web.Mvc source code project in your solution (as if you created it!). This allows you to use Visual Studio’s Go to Declaration command to directly jump any refer- ence in your own source code to the corresponding point in the framework source code, and of course to step into the framework source code when debugging. It can be a huge timesaver when you’re trying to figure out why your application isn’t behaving as expected. This isn’t too difficult to set up, as long as you know about a few likely problems and how to solve them. The instructions may well change after this book is printed, so I’ve put the guide on my blog at http://tinyurl.com/debugMvc. The Request Processing Pipeline We’ve taken an overview of how ASP.NET MVC projects look from Visual Studio’s point of view. Now let’s get an overview of what actually happens at runtime as the MVC Framework processes each incoming request. ASP.NET MVC’s request processing pipeline is comparable to the page life cycle from ASP.NET WebForms, in that it constitutes the anatomy of the system. Having a good grasp of it is essential before you can do anything out of the ordinary. Unlike the traditional ASP.NET page life cycle, MVC’s pipeline is infinitely flexible: you can modify any piece to your own lik- ing, and even rearrange or replace components outright. You don’t usually have to extend or alter the pipeline, but you can—that’s the basis of ASP.NET MVC’s powerful extensibility. For example, while developing SportsStore, you implemented a custom IControllerFactory to instantiate controllers through your IoC container. F igur e 7-8 sho ws a representation of the request processing pipeline. The central, vertical line is the framework’s default pipeline (for requests that render a view); the offshoots are the major extensibility points. ■Note To keep things comprehensible, this diagram doesn’t show every event and extensibility point. The greatest omission is filters, which you can inject before and after running action methods, and before and after executing action results (inc luding ViewResults). For example, in Chapter 6, you used the [Authorize] filter to secure a controller . You’ll hear more about where they fit in later in the chapter. The rest of this chapter descr ibes the request processing pipeline in a little more detail. After that, Chapters 8, 9, and 10 consider each major component in turn, giving you the complete lowdown on ASP.NET MVC’s features and facilities. CHAPTER 7 ■ OVERVIEW OF ASP.NET MVC PROJECTS 213 10078ch07.qxd 3/26/09 12:24 PM Page 213 Figure 7-8. The ASP .NET MVC r equest processing pipeline Stage 1: IIS I nter net Infor mation Ser vices (IIS), Microsoft’s enterprise-grade web server, plays the first part in the request handling pipeline. As each HTTP request arrives, before ASP.NET enters the scene , a kernel-mode Windows device driver called HTTP.SYS considers the r equested URL/por t number/IP addr ess combination, and matches and for war ds it to a r egistered application (which will be either an IIS web site or a virtual directory within an IIS web site). Since ASP.NET MVC applications are built upon ASP.NET, you need to have enabled ASP.NET for that IIS application ’ s application pool (each IIS application is assigned to an application pool). You can enable ASP.NET in one of two managed pipeline modes: CHAPTER 7 ■ OVERVIEW OF ASP.NET MVC PROJECTS214 10078ch07.qxd 3/26/09 12:24 PM Page 214 •In ISAPI mode, also called Classic mode, ASP.NET is invoked through an ISAPI extension ( a spnet_isapi.dll ) , 2 a ssociated with particular URL “file name extensions” (e.g., . aspx , .ashx, .mvc). With IIS 6, you can set up wildcard map so that aspnet_isapi.dll will handle all requests, regardless of URL file name extension. You’ll learn more about deploying MVC Framework applications to IIS 6, including setting up wildcard maps, in Chapter 14. •In Integrated mode (only supported by IIS 7+), .NET is a native part of the IIS request processing pipeline, so you don’t need any ISAPI extension associated with a particular URL file name extension. That makes it easy to use routing configurations with per- fectly clean URLs (i.e., with no file name extension). Either way, once ASP.NET gets hold of an incoming request, it notifies each registered HTTP module that a new request is starting. (An HTTP module is a .NET class, implementing IHttpModule, which you can “plug into” the ASP.NET request processing pipeline.) One particularly important HTTP module is registered by default in any ASP.NET MVC application: UrlRoutingModule. This module is the beginning of the core routing system, which you’ll hear more about in a moment. You can see that it’s registered for IIS 6 by finding the <httpModules> node in your web.config file: <system.web> <httpModules> <add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, " /> </httpModules> </system.web> Or, if you’re running IIS 7, open its Modules GUI (from Administrative Tools, open Internet Information Services (IIS) Manager, select your web site, and then double-click Modules), which edits the <system.webServer>/<modules> node in web.config on your behalf (see Figure 7-9). Figure 7-9. IIS 7’s Modules GUI, showing options for UrlRoutingModule CHAPTER 7 ■ OVERVIEW OF ASP.NET MVC PROJECTS 215 2. Internet Services API (ISAPI) is IIS’s old plug-in system. You can only create ISAPI extensions in unmanaged (e .g., C/C++) code . 10078ch07.qxd 3/26/09 12:24 PM Page 215 Stage 2: Core Routing When UrlRoutingModule gets involved in processing a request, it causes the System.Web.Routing routing system to run. The job of routing is to recognize and parse arbitrary incoming URL p atterns, setting up a r equest context d ata structure that subsequent components can use however they wish (e.g., ASP.NET MVC uses it to transfer control to the relevant MVC con- troller class and to supply action method parameters). From Figure 7-8, you can see that core routing first checks whether the incoming URL corresponds to a file on disk. If it does, then core routing bails out, leaving IIS to handle that request. For static files (e.g., .gif, .jpeg, .png, .css, or .js), this means that IIS will serve them natively (because they exist on disk), which is very efficient. Likewise, it means that traditional ASP.NET WebForms .aspx pages will be executed in the normal way (they exist on disk, too). However, if the incoming URL doesn’t correspond to a file on disk (e.g., requests for MVC controllers, which are .NET types, not files on disk), then core routing investigates its active configuration to figure out how to handle that incoming URL. Routing Configurations Routing configuration is held in a static collection called System.Web.Routing.RouteTable. Routes . Each entry in that collection represents a different URL pattern that you may wish to accept, which may optionally include parameter placeholders (e.g., /blog/{year}/{entry}) and constraints, which limit the range of acceptable values for each parameter. Each entry also specifies a route handler—an object implementing IRouteHandler—which can take over and process the request. You will normally populate the RouteTable.Routes collection by adding code to a method called RegisterRoutes() in your Global.asax.cs file. To match incoming requests to particular RouteTable.Routes entries, the core routing sys- tem simply starts at the top of the RouteTable.Routes collection and scans downward, picking the first entry that matches the incoming request. Having found the matching entry, routing transfers control to that entry’s nominated route handler object, passing it a “request context” data structure that describes the chosen RouteTable.Routes entry and any parameter values parsed from the URL. This is where the real MVC Framework gets in on the action, as you’re about to discover. You’ll find in-depth coverage of the routing system in Chapter 8. Stage 3: Controllers and Actions By now, the routing system has selected a particular RouteTable.Routes entry, and has parsed any routing parameters out of the URL. It’s packaged this information up as a data structure called request context. So, where do controllers and actions enter the scene? Finding and Invoking Controllers F or ASP.NET MVC applications, almost all RouteTable.Routes entr ies specify one particular r oute handler : MvcRouteHandler. That ’ s ASP.NET MVC’s built-in default route handler, and it’s the bridge between core routing and the actual MVC Framework. MvcRouteHandler knows how to take the r equest context data and invoke the corresponding controller class. CHAPTER 7 ■ OVERVIEW OF ASP.NET MVC PROJECTS216 10078ch07.qxd 3/26/09 12:24 PM Page 216 [...]... OVERVIEW OF ASP.NET MVC PROJECTS Summary NET MVC applications from two perspectives: This chapter presented an overview of ASP • From a project structure perspective, you saw how the default MVC Visual Studio project templates work, and how code files are laid out by default You learned which files, folders, and naming conventions are merely suggestions, and which are actually required by the framework. .. originally shipped with NET 3 .5 SP1—long before ASP.NET MVC was released—so that it could be used by ASP.NET Dynamic Data applications It’s likely that the forthcoming ASP.NET 4.0 (to be included in Visual Studio 2010) will be able to use the routing system, too, giving WebForms developers a sensible way to achieve clean URLs This chapter focuses on how to use routing with ASP.NET MVC, but much of the information... such as custom 404 handlers and URL-rewriting ISAPI filters, can be hard to set up and come with their own problems Putting the Programmer Back in Control ASP.NET MVC is different URLs are not expected to correspond to files on your web server In fact, that wouldn’t even make sense—since ASP.NET MVC s requests are handled by controller classes (compiled into a NET assembly), there are no particular files... of the MVC Framework You’ll learn much more about them in Chapter 9 217 10078ch07.qxd 218 3/26/09 12:24 PM Page 218 CHAPTER 7 I OVERVIEW OF ASP.NET MVC PROJECTS Stage 4: Action Results and Views OK, quite a lot has happened! Let’s recap: • The routing system matched the incoming URL to its configuration and prepared a request context data structure The matching RouteTable.Route entry nominated MvcRouteHandler... ASP.NET MVC adds an extension method on to RouteCollection, called MapRoute() This provides an alternative syntax for adding route entries You might find it more convenient You could express the same route entry as follows: routes.MapRoute("PublicProductsList", "Catalog", new { controller = "Products", action = "List" }); In this case, PublicProductsList is the name of the route entry It’s just an arbitrary... into the URL That means you can get cleaner, shorter URLs For example, will render the following (assuming that Index is the default value for action): Products homepage Notice the URL generated here is /Products, not /Products/Index There would be no point putting Index in the URL, because that’s configured as... /Forum/ShowTopics/ 75 { controller = "Forum", action = "ShowTopics", id = " 75" } There are five properties you can configure on each RouteTable entry These affect whether or not it matches a given URL, and if it does, what happens to the request (see Table 8-4) 223 10078ch08.qxd 224 3/16/09 12:40 PM Page 224 CHAPTER 8 I URLS AND ROUTING Table 8-4 Properties of System.Web.Routing.Route Property Meaning... Understanding the Routing Mechanism The routing mechanism runs early in the framework s request processing pipeline Its job is to take an incoming URL and use it to obtain an IHttpHandler object that will handle the request Many newcomers to the MVC Framework struggle with routing It isn’t comparable to anything in traditional ASP.NET, and it’s easy to configure wrongly By understanding its inner workings,... Route("Catalog", new MvcRouteHandler()) { Defaults = new RouteValueDictionary { { "controller", "Products" }, { "action", "List" } } }); Either way, RouteValueDictionary is ultimately just a dictionary, so it’s not very type-safe and offers no IntelliSense—so there’s nothing to stop you from mistyping conrtoller, and you won’t find out until an error occurs at runtime Take a Shortcut with MapRoute() ASP.NET MVC adds... "AnnualReview" } This is all managed by the framework s routing system Once you’ve supplied your desired routing configuration, the routing system does two main things: 1 Maps each incoming URL to the appropriate request handler class 2 Constructs outgoing URLs (i.e., to other parts of your application) The core ASP.NET routing system is totally independent of the rest of the MVC Framework That’s why it lives in . how ASP. NET MVC projects look from Visual Studio’s point of view. Now let’s get an overview of what actually happens at runtime as the MVC Framework processes each incoming request. ASP. NET MVC s. yourself. Stepping into the ASP. NET MVC Source Code Since you can download the whole ASP. NET MVC Framework source code package, it’s possi- ble to include the System.Web .Mvc source code project in your. facilities. CHAPTER 7 ■ OVERVIEW OF ASP. NET MVC PROJECTS 213 10078ch07.qxd 3/26/09 12:24 PM Page 213 Figure 7-8. The ASP .NET MVC r equest processing pipeline Stage 1: IIS I nter net Infor mation Ser vices

Ngày đăng: 06/08/2014, 08:22

TỪ KHÓA LIÊN QUAN