Tải bản đầy đủ (.pdf) (778 trang)

Apress Pro ASP NET MVC 2 Framework 2nd edition

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (9.93 MB, 778 trang )

  CYAN
  MAGENTA

  YELLOW
  BLACK
  PANTONE 123 C

BOOKS FOR PROFESSIONALS BY PROFESSIONALS đ

Pro ASP.NET MVC 2 Framework

Pro ASP.NET MVC
Framework

ã The MVC Framework’s powerful facilities, including routing, controllers, filters,
views, model metadata, model binding, and validation
• Architecture, including the model-view-controller (MVC) pattern, test-driven
development (TDD), behavior-driven development (BDD), and relevant design
patterns such as dependency injection
• Extending and customizing the MVC Framework’s request processing pipeline
• Securing your MVC application and deploying it to Windows Server
• Upgrading from ASP
.NET MVC 1, and integrating with or upgrading from
traditional ASP
.NET (also known as Web Forms)
This book does not assume that you have any existing knowledge of ASP
.NET
MVC. It assumes only that you have a working knowledge of C# and some web
development experience. Enjoy,
Steven Sanderson
Companion eBook



THE APRESS ROADMAP
Introducing
.NET 4.0

Pro C# 2010
and the
.NET 4 Platform

See last page for details
on $10 eBook version

Accelerated
C# 2010

Pro
ASP.NET MVC 2
Pro
Silverlight 4 in C#

Pro ASP.NET 4
in C# 2010

SOURCE CODE ONLINE

www.apress.com

ISBN 978-1-4302-2886-8
5 54 9 9


US $54.99

Pro

SECOND
EDITION

Sanderson

Pro
LINQ

Companion
eBook Available

ASP.NET MVC 2

Steven Sanderson,
Author of

Microsoft’s ASP
.NET MVC Framework has dramatically shifted .NET web development into the modern age. It promotes maintainability through clean architecture and separation of concerns, tight control over HTML and URLs, unit
testability, powerful extensibility, and easy integration with third-party libraries
such as jQuery. Now, based on real-world feedback, version 2 of the framework
adds many valuable enhancements for security, scalability, and simplifying data
entry and validation.
The original edition of this book was the highest rated and best selling of all
books on ASP
.NET MVC, so I was excited by the chance to update it and build on
that success. My hope is that this new edition will give you the deepest understanding of everything that ASP

.NET MVC 2 offers. You’ll find major new sections about
the framework’s new version 2 features, and the whole book is thoroughly revised
and expanded to account for .NET 4 and the latest best practices. You’ll learn about:

THE EXPERT’S VOICE ® IN .NET

Pro

ASP.NET MVC 2
Framework
www.free-ebooks-download.org

Build the most maintainable, standards-compliant, and best
performing web applications on the Microsoft platform

SECOND EDITION

Steven Sanderson

Shelve in:
.NET
User level:
Intermediate–Advanced

9 7814
30 228868

this print for content only—size & color not accurate

7.5 x 9.5 spine =1.46875 776 page count



     

www.free-ebooks-download.org


Pro ASP.NET MVC 2
Framework
Download from Library of Wow! eBook
www.wowebook.com

www.free-ebooks-download.org

■■■
Steven Sanderson

i


Pro ASP.NET MVC 2 Framework
Copyright © 2010 by Steven Sanderson
All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means,
electronic or mechanical, including photocopying, recording, or by any information storage or retrieval
system, without the prior written permission of the copyright owner and the publisher.
ISBN-13 (pbk): 978-1-4302-2886-8
ISBN-13 (electronic): 978-1-4302-2887-5
Printed and bound in the United States of America 9 8 7 6 5 4 3 2 1
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol
with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only

in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of
the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are
not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject
to proprietary rights.
President and Publisher: Paul Manning
Lead Editor: Ewan Buckingham
Main Technical Reviewer: Stefan Turalski
Additional Technical Reviewers: Jimmy Skowronski, Bryan Avery
Editorial Board: Clay Andres, Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell,
Jonathan Gennick, Jonathan Hassell, Michelle Lowman, Matthew Moodie, Duncan Parkes,
Jeffrey Pepper, Frank Pohlmann, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft,
Matt Wade, Tom Welsh
Coordinating Editor: Anne Collett
Copy Editor: Damon Larson
Compositor: MacPS, LLC
Indexer: BIM Indexing & Proofreading Services
Artist: April Milne
Cover Designer: Anna Ishchenko

www.free-ebooks-download.org

Distributed to the book trade worldwide by Springer Science+Business Media, LLC., 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail , or visit www.springeronline.com.
For information on translations, please e-mail , or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our
Special Bulk Sales–eBook Licensing web page at www.apress.com/info/bulksales.
The information in this book is distributed on an “as is” basis, without warranty. Although every
precaution has been taken in the preparation of this work, neither the author(s) nor Apress shall have

any liability to any person or entity with respect to any loss or damage caused or alleged to be caused
directly or indirectly by the information contained in this work.
The source code for this book is available to readers at www.apress.com.

ii


To Zoe, who once again loved and supported me throughout this project

www.free-ebooks-download.org

iii


Contents at a Glance

■Contents at a Glance........................................................................................................ iv
■Contents............................................................................................................................ v
■About the Author .............................................................................................................xx
■About the Technical Reviewers ......................................................................................xxi
■Acknowledgments .........................................................................................................xxii
■Introduction ..................................................................................................................xxiii
Part 1: Introducing ASP.NET MVC 2 ..................................................................................... 1
■Chapter 1: What’s the Big Idea? ....................................................................................... 3
■Chapter 2: Your First ASP.NET MVC Application............................................................. 15
■Chapter 3: Prerequisites................................................................................................. 43
■Chapter 4: SportsStore: A Real Application .................................................................... 91
■Chapter 5: SportsStore: Navigation and Shopping Cart................................................ 135
■Chapter 6: SportsStore: Administration and Final Enhancements ............................... 179
Part 2: ASP.NET MVC in Detail ......................................................................................... 213

■Chapter 7: Overview of ASP.NET MVC Projects.............................................................. 215
■Chapter 8: URLs and Routing ........................................................................................ 235
■Chapter 9: Controllers and Actions............................................................................... 283
■Chapter 10: Controller Extensibility.............................................................................. 325
■Chapter 11: Views......................................................................................................... 373
■Chapter 12: Models and Data Entry .............................................................................. 409
■Chapter 13: User Interface Techniques ........................................................................ 477
■Chapter 14: Ajax and Client Scripting........................................................................... 517
Part 3: Delivering Successful ASP.NET MVC 2 Projects ................................................... 561
■Chapter 15: Security and Vulnerability......................................................................... 563
■Chapter 16: Deployment ............................................................................................... 585
■Chapter 17: ASP.NET Platform Features ....................................................................... 619
■Chapter 18: Upgrading and Combining ASP.NET Technologies .................................... 675
■Index............................................................................................................................. 701

iv


Contents
■Contents at a Glance ............................................................................................iv
■Contents ................................................................................................................v
■About the Author ................................................................................................. xx
■About the Technical Reviewers.......................................................................... xxi
■Acknowledgments............................................................................................. xxii
■Introduction...................................................................................................... xxiii
Part 1: Introducing ASP.NET MVC 2..........................................................................1
■Chapter 1: What’s the Big Idea?............................................................................3
A Brief History of Web Development............................................................................... 3
Traditional ASP.NET Web Forms ............................................................................................................4
What’s Wrong with ASP.NET Web Forms? .............................................................................................5


Web Development Today ................................................................................................ 6
Web Standards and REST ......................................................................................................................6
Agile and Test-Driven Development.......................................................................................................7
Ruby on Rails .........................................................................................................................................7

Key Benefits of ASP.NET MVC ......................................................................................... 8
MVC Architecture ...................................................................................................................................8
Extensibility............................................................................................................................................8
Tight Control over HTML and HTTP ........................................................................................................9
Testability...............................................................................................................................................9
Powerful Routing System.....................................................................................................................10
Built on the Best Parts of the ASP.NET Platform..................................................................................10

v


■ CONTENTS

Modern API...........................................................................................................................................11
ASP.NET MVC Is Open Source ..............................................................................................................11

Who Should Use ASP.NET MVC? ................................................................................... 11
Comparisons with ASP.NET Web Forms ..............................................................................................11
Comparisons with Ruby on Rails .........................................................................................................12
Comparisons with MonoRail ................................................................................................................13

What’s New in ASP.NET MVC 2 ..................................................................................... 13
Summary....................................................................................................................... 14
■Chapter 2: Your First ASP.NET MVC Application .................................................15

Preparing Your Workstation .......................................................................................... 15
Creating a New ASP.NET MVC Project .......................................................................... 16
Adding the First Controller ...................................................................................................................18
How Does It Know to Invoke HomeController?.....................................................................................19

Rendering Web Pages................................................................................................... 19
Creating and Rendering a View............................................................................................................19
Adding Dynamic Output .......................................................................................................................22

A Starter Application ..................................................................................................... 23
The Story..............................................................................................................................................23
Designing a Data Model .......................................................................................................................24
Linking Between Actions......................................................................................................................25
Building a Form....................................................................................................................................29
Handling Form Submissions ................................................................................................................32
Adding Validation .................................................................................................................................35
Finishing Off.........................................................................................................................................39

Summary....................................................................................................................... 41
■Chapter 3: Prerequisites .....................................................................................43
Understanding MVC Architecture.................................................................................. 43
The Smart UI (Anti-Pattern)..................................................................................................................44
Separating Out the Domain Model .......................................................................................................45

vi


■ CONTENTS

Three-Tier Architecture........................................................................................................................46

MVC Architecture .................................................................................................................................47
Variations on MVC ................................................................................................................................49

Domain Modeling .......................................................................................................... 50
An Example Domain Model ..................................................................................................................51
Ubiquitous Language ...........................................................................................................................52
Aggregates and Simplification .............................................................................................................52
Keeping Data Access Code in Repositories..........................................................................................54
Using LINQ to SQL ................................................................................................................................55

Building Loosely Coupled Components......................................................................... 61
Taking a Balanced Approach ...............................................................................................................62
Using Dependency Injection.................................................................................................................62
Using a DI Container.............................................................................................................................64

Getting Started with Automated Testing....................................................................... 66
Understanding Unit Testing..................................................................................................................67
Understanding Integration Testing.......................................................................................................73

C# 3 Language Features ............................................................................................... 78
The Design Goal: Language-Integrated Query .....................................................................................78
Extension Methods...............................................................................................................................79
Lambda Methods .................................................................................................................................80
Generic Type Inference ........................................................................................................................81
Automatic Properties ...........................................................................................................................81
Object and Collection Initializers..........................................................................................................82
Type Inference .....................................................................................................................................82
Anonymous Types ................................................................................................................................83
Using LINQ to Objects...........................................................................................................................85
Lambda Expressions ............................................................................................................................86

IQueryable<T> and LINQ to SQL ..........................................................................................................87

Summary....................................................................................................................... 89
■Chapter 4: SportsStore: A Real Application.........................................................91

vii


■ CONTENTS

Getting Started.............................................................................................................. 93
Creating Your Solutions and Projects...................................................................................................93

Starting Your Domain Model ......................................................................................... 96
Creating an Abstract Repository ..........................................................................................................97
Making a Fake Repository....................................................................................................................98

Displaying a List of Products ........................................................................................ 98
Adding the First Controller ...................................................................................................................99
Setting Up the Default Route..............................................................................................................100
Adding the First View .........................................................................................................................101

Connecting to a Database ........................................................................................... 104
Defining the Database Schema..........................................................................................................104
Setting Up LINQ to SQL.......................................................................................................................107
Creating a Real Repository.................................................................................................................107

Setting Up DI ............................................................................................................... 109
Creating a Custom Controller Factory ................................................................................................109
Using Your DI Container .....................................................................................................................110


Creating Unit Tests...................................................................................................... 113
Configuring a Custom URL Schema ............................................................................ 118
Assigning a Default Parameter Value.................................................................................................119
Displaying Page Links ........................................................................................................................120
Improving the URLs............................................................................................................................128

Styling It Up................................................................................................................. 129
Defining Page Layout in the Master Page ..........................................................................................129
Adding CSS Rules...............................................................................................................................130
Creating a Partial View.......................................................................................................................132

Summary..................................................................................................................... 134
■Chapter 5: SportsStore: Navigation and Shopping Cart ....................................135
Adding Navigation Controls......................................................................................... 135
Filtering the Product List....................................................................................................................135

viii


■ CONTENTS

Defining a URL Schema for Categories ..............................................................................................139
Building a Category Navigation Menu ................................................................................................141

Building the Shopping Cart ......................................................................................... 149
Defining the Cart Entity ......................................................................................................................149
Adding “Add to Cart” Buttons ............................................................................................................152
Giving Each Visitor a Separate Shopping Cart ...................................................................................154
Creating CartController ......................................................................................................................155

Displaying the Cart.............................................................................................................................159
Removing Items from the Cart ...........................................................................................................162
Displaying a Cart Summary in the Title Bar .......................................................................................163

Submitting Orders....................................................................................................... 165
Enhancing the Domain Model ............................................................................................................165
Adding the “Check Out Now” Button .................................................................................................166
Prompting the Customer for Shipping Details....................................................................................167
Defining an Order Submitter DI Component.......................................................................................169
Completing CartController..................................................................................................................169
Implementing EmailOrderSubmitter...................................................................................................175

Summary..................................................................................................................... 178
■Chapter 6: SportsStore: Administration and Final Enhancements ....................179
Adding Catalog Management...................................................................................... 180
Creating AdminController: A Place for the CRUD Features.................................................................180
Rendering a Grid of Products in the Repository .................................................................................182
Building a Product Editor ...................................................................................................................186
Creating New Products ......................................................................................................................194
Deleting Products...............................................................................................................................196

Securing the Administration Features ........................................................................ 198
Setting Up Forms Authentication .......................................................................................................198
Using a Filter to Enforce Authentication.............................................................................................199
Displaying a Login Prompt .................................................................................................................200

Image Uploads ............................................................................................................ 204

ix



■ CONTENTS

Preparing the Domain Model and Database.......................................................................................204
Accepting File Uploads.......................................................................................................................205
Displaying Product Images ................................................................................................................209

Summary..................................................................................................................... 212
Part 2: ASP.NET MVC in Detail ..............................................................................213
■Chapter 7: Overview of ASP.NET MVC Projects..................................................215
Developing MVC Applications in Visual Studio............................................................ 215
Naming Conventions ..........................................................................................................................220
The Initial Application Skeleton..........................................................................................................220
Debugging MVC Applications and Unit Tests .....................................................................................221
Using the Debugger ...........................................................................................................................224
Stepping into the .NET Framework Source Code ...............................................................................225
Stepping into the ASP.NET MVC Framework Source Code ................................................................226

The Request Processing Pipeline................................................................................ 227
Stage 1: IIS.........................................................................................................................................229
Stage 2: Core Routing ........................................................................................................................230
Stage 3: Controllers and Actions........................................................................................................231
Stage 4: Action Results and Views.....................................................................................................232

Summary..................................................................................................................... 233
■Chapter 8: URLs and Routing.............................................................................235
Putting the Programmer Back in Control .................................................................... 235
About Routing and Its .NET Assemblies .............................................................................................236

Setting Up Routes ....................................................................................................... 236

Understanding the Routing Mechanism.............................................................................................239
Adding a Route Entry .........................................................................................................................241
Using Parameters...............................................................................................................................243
Using Defaults....................................................................................................................................244
Using Constraints ...............................................................................................................................245
Prioritizing Controllers by Namespace...............................................................................................248
Accepting a Variable-Length List of Parameters................................................................................249

x


■ CONTENTS

Matching Files on the Server’s Hard Disk..........................................................................................250
Using IgnoreRoute to Bypass the Routing System.............................................................................251

Generating Outgoing URLs .......................................................................................... 252
Generating Hyperlinks with Html.ActionLink() ...................................................................................252
Generating Links and URLs from Pure Routing Data..........................................................................255
Performing Redirections to Generated URLs......................................................................................256
Understanding the Outbound URL-Matching Algorithm .....................................................................256
Generating Hyperlinks with Html.ActionLink<T> and Lambda Expressions......................................259
Working with Named Routes .............................................................................................................260

Working with Areas..................................................................................................... 261
Setting Up Areas ................................................................................................................................261
Routing and URL Generation with Areas ............................................................................................264
Areas and the Ambiguous Controller Problem ...................................................................................267
Areas Summary..................................................................................................................................267


Unit Testing Your Routes............................................................................................. 267
Testing Inbound URL Routing.............................................................................................................268
Testing Outbound URL Generation .....................................................................................................272

Further Customization................................................................................................. 274
Implementing a Custom RouteBase Entry..........................................................................................275
Implementing a Custom Route Handler .............................................................................................276

URL Schema Best Practices........................................................................................ 277
Make Your URLs Clean and Human-Friendly .....................................................................................277
Follow HTTP Conventions...................................................................................................................278
SEO.....................................................................................................................................................281

Summary..................................................................................................................... 281
■Chapter 9: Controllers and Actions ...................................................................283
An Overview ................................................................................................................ 283
Comparisons with ASP.NET Web Forms ............................................................................................284
All Controllers Implement IController .................................................................................................284
The Controller Base Class ..................................................................................................................285

xi


■ CONTENTS

Receiving Input ........................................................................................................... 286
Getting Data from Context Objects.....................................................................................................287
Using Action Method Parameters.......................................................................................................288
Invoking Model Binding Manually in an Action Method .....................................................................291


Producing Output ........................................................................................................ 292
Understanding the ActionResult Concept...........................................................................................292
Returning HTML by Rendering a View................................................................................................295
Performing Redirections ....................................................................................................................300
Returning Textual Data ......................................................................................................................304
Returning JSON Data .........................................................................................................................306
Returning JavaScript Commands.......................................................................................................307
Returning Files and Binary Data ........................................................................................................308
Creating a Custom Action Result Type...............................................................................................311

Unit Testing Controllers and Actions........................................................................... 313
How to Arrange, Act, and Assert ........................................................................................................314
Testing a Choice of View and ViewData.............................................................................................314
Testing Redirections ..........................................................................................................................316
More Comments About Unit Testing ..................................................................................................317
Mocking Context Objects ...................................................................................................................317
Reducing the Pain of Mocking ...........................................................................................................319

Summary..................................................................................................................... 324
■Chapter 10: Controller Extensibility ..................................................................325
Using Filters to Attach Reusable Behaviors ................................................................ 325
Introducing the Four Basic Types of Filter .........................................................................................326
Applying Filters to Controllers and Action Methods ...........................................................................327
Creating Action Filters and Result Filters...........................................................................................328
Creating and Using Authorization Filters............................................................................................333
Creating and Using Exception Filters .................................................................................................336
Bubbling Exceptions Through Action and Result Filters ....................................................................340
The [OutputCache] Action Filter .........................................................................................................341

xii



■ CONTENTS

The [RequireHttps] Filter....................................................................................................................344
Other Built-In Filter Types ..................................................................................................................344

Controllers As Part of the Request Processing Pipeline.............................................. 344
Working with DefaultControllerFactory ..............................................................................................345
Creating a Custom Controller Factory ................................................................................................348
Customizing How Action Methods Are Selected and Invoked............................................................349
Overriding HTTP Methods to Support REST Web Services.................................................................355

Boosting Server Capacity with Asynchronous Controllers .......................................... 357
Introducing Asynchronous Requests..................................................................................................358
Using Asynchronous Controllers ........................................................................................................358
Adding Asynchronous Methods to Domain Classes ...........................................................................367
Choosing When to Use Asynchronous Controllers .............................................................................368

Summary..................................................................................................................... 371
■Chapter 11: Views .............................................................................................373
How Views Fit into ASP.NET MVC ............................................................................... 373
The Web Forms View Engine..............................................................................................................374
View Engines Are Replaceable...........................................................................................................374

Web Forms View Engine Basics.................................................................................. 374
Adding Content to a View...................................................................................................................374
Five Ways to Add Dynamic Content to a View....................................................................................375

Using Inline Code ........................................................................................................ 376

Why Inline Code Is a Good Thing in MVC Views .................................................................................378

Understanding How MVC Views Actually Work........................................................... 378
Understanding How ASPX Pages Are Compiled .................................................................................378
How Automatic HTML Encoding Works..............................................................................................381
Understanding ViewData....................................................................................................................384
Extracting ViewData Items Using ViewData.Eval ...............................................................................385

Using HTML Helper Methods....................................................................................... 386
The Framework’s Built-In Helper Methods ........................................................................................387
Creating Your Own HTML Helper Methods.........................................................................................399

xiii


■ CONTENTS

Using Partial Views ..................................................................................................... 401
Creating and Rendering a Partial View ..............................................................................................401
Rendering a Partial View Using Server Tags......................................................................................406

Summary..................................................................................................................... 408
■Chapter 12: Models and Data Entry...................................................................409
How It All Fits Together............................................................................................... 409
Templated View Helpers ............................................................................................. 410
Displaying and Editing Models Using Templated View Helpers .........................................................411
Using Partial Views to Define Custom Templates ..............................................................................422

Model Metadata .......................................................................................................... 427
Working with Data Annotations..........................................................................................................428

Creating a Custom Metadata Provider ...............................................................................................429
Consuming Model Metadata in Custom HTML Helpers ......................................................................433
Using [MetadataType] to Define Metadata on a Buddy Class ............................................................434

Model Binding ............................................................................................................. 434
Model-Binding to Action Method Parameters ....................................................................................435
Model-Binding to Custom Types ........................................................................................................436
Invoking Model Binding Directly ........................................................................................................439
Model-Binding to Arrays, Collections, and Dictionaries.....................................................................441
Creating a Custom Value Provider .....................................................................................................444
Creating a Custom Model Binder .......................................................................................................445
Using Model Binding to Receive File Uploads ....................................................................................449

Validation .................................................................................................................... 450
Registering and Displaying Validation Errors.....................................................................................450
Performing Validation As Part of Model Binding ................................................................................456
Specifying Validation Rules................................................................................................................458
Invoking Validation Manually .............................................................................................................464
Using Client-Side Validation...............................................................................................................465
Putting Your Model Layer in Charge of Validation..............................................................................472

Summary..................................................................................................................... 476

xiv


■ CONTENTS

■Chapter 13: User Interface Techniques .............................................................477
Wizards and Multistep Forms ..................................................................................... 477

Defining the Model.............................................................................................................................478
Navigation Through Multiple Steps ....................................................................................................479
Collecting and Preserving Data..........................................................................................................481
Completing the Wizard.......................................................................................................................483
Validation ...........................................................................................................................................485

Implementing a CAPTCHA ........................................................................................... 489
Creating an Html.Captcha() Helper.....................................................................................................490
Verifying the Form Submission ..........................................................................................................495

Using Child Actions to Create Reusable Widgets with Application Logic.................... 496
How the Html.RenderAction Helper Invokes Child Actions ................................................................497
When It’s Appropriate to Use Child Actions........................................................................................497
Creating a Widget Based on a Child Action........................................................................................498
Capturing a Child Action’s Output As a String....................................................................................501
Detecting Whether You’re Inside a Child Request..............................................................................501
Restricting an Action to Handle Child Requests Only.........................................................................502

Sharing Page Layouts Using Master Pages ................................................................ 502
Using Widgets in MVC View Master Pages.........................................................................................503

Implementing a Custom View Engine ......................................................................... 505
A View Engine That Renders XML Using XSLT ...................................................................................505

Using Alternative View Engines .................................................................................. 510
Using the NVelocity View Engine .......................................................................................................511
Using the Brail View Engine ...............................................................................................................512
Using the NHaml View Engine............................................................................................................513
Using the Spark View Engine .............................................................................................................514


Summary..................................................................................................................... 515
■Chapter 14: Ajax and Client Scripting ...............................................................517
Why You Should Use a JavaScript Toolkit................................................................... 517

xv


■ CONTENTS

ASP.NET MVC’s Ajax Helpers ...................................................................................... 518
Fetching Page Content Asynchronously Using Ajax.ActionLink .........................................................519
Submitting Forms Asynchronously Using Ajax.BeginForm ................................................................525
Invoking JavaScript Commands from an Action Method ...................................................................526
Reviewing ASP.NET MVC’s Ajax Helpers............................................................................................528

Using jQuery with ASP.NET MVC................................................................................. 529
Referencing jQuery ............................................................................................................................530
Basic jQuery Theory ...........................................................................................................................532
Adding Client-Side Interactivity to an MVC View................................................................................537
Ajax-Enabling Links and Forms .........................................................................................................542
Client/Server Data Transfer with JSON..............................................................................................548
Performing Cross-Domain JSON Requests Using JSONP ..................................................................552
Fetching XML Data Using jQuery........................................................................................................554
Animations and Other Graphical Effects ............................................................................................555
jQuery UI’s Prebuilt UI Widgets ..........................................................................................................556
Summarizing jQuery...........................................................................................................................558

Summary..................................................................................................................... 559
Part 3: Delivering Successful ASP.NET MVC 2 Projects .......................................561
■Chapter 15: Security and Vulnerability .............................................................563

All Input Can Be Forged .............................................................................................. 563
Forging HTTP Requests......................................................................................................................565

Cross-Site Scripting and HTML Injection .................................................................... 567
Example XSS Vulnerability .................................................................................................................568
ASP.NET’s Request Validation Feature...............................................................................................569
Filtering HTML Using the HTML Agility Pack ......................................................................................572
JavaScript String Encoding and XSS .................................................................................................574

Session Hijacking........................................................................................................ 575
Defense via Client IP Address Checks................................................................................................576
Defense by Setting the HttpOnly Flag on Cookies..............................................................................576

Cross-Site Request Forgery ........................................................................................ 577

xvi


■ CONTENTS

Attack.................................................................................................................................................577
Defense ..............................................................................................................................................578
Preventing CSRF Using the Anti-Forgery Helpers ..............................................................................578

SQL Injection ............................................................................................................... 580
Attack.................................................................................................................................................581
Defense by Encoding Inputs...............................................................................................................581
Defense Using Parameterized Queries...............................................................................................581
Defense Using Object-Relational Mapping.........................................................................................582


Using the MVC Framework Securely........................................................................... 582
Don’t Expose Action Methods Accidentally........................................................................................582
Don’t Allow Model Binding to Change Sensitive Properties...............................................................583

Summary..................................................................................................................... 583
■Chapter 16: Deployment....................................................................................585
Server Requirements .................................................................................................. 585
Requirements for Shared Hosting......................................................................................................586

Building Your Application for Production Use ............................................................. 586
Controlling Dynamic Page Compilation..............................................................................................586
Detecting Compiler Errors in Views Before Deployment....................................................................587

IIS Basics .................................................................................................................... 588
Understanding Web Sites and Virtual Directories ..............................................................................589
Binding Web Sites to Hostnames, IP Addresses, and Ports ...............................................................590

Deploying Your Application ......................................................................................... 590
Manually Copying Application Files to the Server..............................................................................590
Bin-Deploying ASP.NET MVC 2...........................................................................................................591
Deploying to IIS 6 on Windows Server 2003 ......................................................................................593
Deploying to IIS 7.x on Windows Server 2008/2008 R2.....................................................................602
Deploying to IIS 7.5 on Windows Server 2008 R2 Core......................................................................609

Automating Deployments with WebDeploy and Visual Studio 2010 ........................... 610
Transforming Configuration Files.......................................................................................................612
Automating Online Deployments with One-Click Publishing..............................................................615

xvii



■ CONTENTS

Automating Offline Deployments with Packaging..............................................................................616

Summary..................................................................................................................... 618
■Chapter 17: ASP.NET Platform Features............................................................619
Windows Authentication ............................................................................................. 620
Preventing or Limiting Anonymous Access........................................................................................622

Forms Authentication.................................................................................................. 623
Setting Up Forms Authentication .......................................................................................................624
Using Cookieless Forms Authentication.............................................................................................627

Membership, Roles, and Profiles ................................................................................ 628
Setting Up a Membership Provider ....................................................................................................630
Using a Membership Provider with Forms Authentication.................................................................635
Creating a Custom Membership Provider ..........................................................................................636
Setting Up and Using Roles................................................................................................................637
Setting Up and Using Profiles ............................................................................................................640

URL-Based Authorization ............................................................................................ 644
Configuration .............................................................................................................. 644
Configuring Connection Strings .........................................................................................................645
Configuring Arbitrary Key/Value Pairs................................................................................................646
Defining Configuration Sections to Configure Arbitrary Data Structures ...........................................646

Data Caching............................................................................................................... 648
Reading and Writing Cache Data .......................................................................................................648
Using Advanced Cache Features........................................................................................................651


Site Maps .................................................................................................................... 652
Setting Up and Using Site Maps.........................................................................................................653
Creating a Custom Navigation Control with the Site Maps API ..........................................................654
Generating Site Map URLs from Routing Data ...................................................................................655

Internationalization ..................................................................................................... 658
Setting Up Localization ......................................................................................................................659
Tips for Working with Resource Files ................................................................................................662
Using Placeholders in Resource Strings ............................................................................................662

xviii


■ CONTENTS

Internationalizing Validation...............................................................................................................663
Localizing Data Annotations Validation Messages.............................................................................665

Performance ............................................................................................................... 667
HTTP Compression.............................................................................................................................667
Tracing and Monitoring......................................................................................................................669
Monitoring Page Generation Times....................................................................................................670
Monitoring LINQ to SQL Database Queries.........................................................................................671

Summary..................................................................................................................... 674
■Chapter 18: Upgrading and Combining ASP.NET Technologies.........................675
Using ASP.NET MVC in a Web Forms Application ....................................................... 675
Upgrading an ASP.NET Web Forms Application to Support MVC .......................................................676
Interactions Between Web Forms Pages and MVC Controllers..........................................................683


Using Web Forms Technologies in an MVC Application .............................................. 686
Using Web Forms Controls in MVC Views ..........................................................................................686
Using Web Forms Pages in an MVC Web Application ........................................................................688
Adding Routing Support for Web Forms Pages..................................................................................689

Upgrading from ASP.NET MVC 1 ................................................................................. 694
Using Visual Studio 2010’s Built-In Upgrade Wizard..........................................................................695
Other Ways to Upgrade ......................................................................................................................697
A Post-Upgrade Checklist ..................................................................................................................697

Summary..................................................................................................................... 700
■Index .................................................................................................................701

xix


■ CONTENTS

About the Author

■ Steven Sanderson first learned to program computers by copying BASIC
listings from a Commodore VIC-20 instruction manual. That was also how he
first learned to read.
Steve was born in Sheffield, United Kingdom, got his education by
studying mathematics at Cambridge, and now lives in Bristol. He worked for a
giant investment bank, a tiny startup company, and then a medium-sized ISV
before going independent as a freelance web developer, consultant, and
trainer. Steve enjoys the United Kingdom’s .NET community and participates
in user groups and speaks at free conferences whenever he has the chance.

Steve loves all forms of technological progress and will buy any gadget if it
has flashing LEDs.

xx


■ CONTENTS

About the Technical Reviewers

■ Stefan Turalski is a nice chap who is capable of performing both magic and trivial things, with a little
help of code, libraries, tools, APIs, servers, and the like.
Wearing many hats, he has experienced almost all aspects of the software life cycle, and is especially
skilled in business analysis, design, implementation, testing and QA, and team management.
His main area of interest is quite wide and could be summarized as emerging technologies, with
recent focus on .NET 4, mobile development, functional programming, and software engineering at
large.
Before he realized that he enjoys criticizing other people’s work more, Stefan published several
technical articles, mainly about .NET technology, SOA, and software engineering. For the last 10-plus
years he has been building solutions ranging from Perl scripts, embedded systems, and web sites, to
highly scalable C++/Java/.NET enterprise class systems.Feel free contact him at

■ Jimmy Skowronski is a developer and architect working for Symantec Hosted Services, based in the
United Kingdom. He has been working with .NET since the beta 1 days, mainly focusing on the web side
of the stack. He is also the founder and leader of the Gloucester .NET user group.
Jimmy enjoys hiking, mountaineering, and skiing. He lives in Gloucester with his wife, Kate, and two
cats, Bobby and Yoda.
■ Bryan Avery has worked with Microsoft technologies for over 20 years. He’s built software for some of
the world’s leading private and public sector companies, applying both technical knowledge and
managerial expertise. His innovative and pioneering projects for Britain’s National Health Service have

helped to save thousands of lives, and his work to streamline commercial business processes has helped
to save millions of dollars.
Currently, Bryan’s preferred technology stack includes C#, ASP.NET MVC, and SQL Server. He also
knows VB .NET and isn’t afraid to use it. In his spare time, he keeps fit by taking part in triathalons. He
completed the French Ironman competition held in Nice.

xxi


■ CONTENTS

Acknowledgments
First, I’d like to thank all the readers of my first ASP.NET MVC book who e-mailed me with feedback and
constructive suggestions for this new edition. Many of the improvements in this manuscript, small and
large, are due to that feedback. Thanks also to those who took the time to write honest reviews on
Amazon—these have a significant influence on sales, and as such are part of what has made this new
edition possible.
Throughout this project, the team at Apress has been professional and reliable, and has done
everything possible to simplify my job. Ewan got things started, and made it easy to agree on contractual
details and the main table of contents. I thank Anne, the project manager, for her flexibility and
confidence as we adapted our schedules. It’s been a pleasure to work again with Damon, who expertly
reorganized each unclear sentence and never seems to misses a grammar error. Stefan, the main
technical reviewer, patiently tracked down any differences in my code’s behavior on .NET 3.5 SP1 vs.
.NET 4. Any technical errors that remain will be the ones that I secretly inserted after Stefan had
completed his reviews.
Of course, thanks are also due to the ASP.NET MVC 2 team at Microsoft. In the 12 months since
ASP.NET MVC 1 launched, Phil Haack, Scott Guthrie, and their clever colleagues have blogged, tweeted,
traveled, presented, podcasted, polled, e-mailed, and listened to find out about developers’ real
experiences of the MVC Framework. They enhanced the framework in the ways we all wanted, kept the
whole thing open source, and gave us preview releases every few months so the community could be

involved in the design process.

xxii


Introduction
This book is for professional software developers who already have a working understanding of C# and
general web development concepts such as HTML and HTTP. Many readers will have background
knowledge of traditional ASP.NET (now known as Web Forms, to distinguish it from MVC), so in many
places I point out the similarities of and differences between the two ASP.NET technologies. But if you’ve
used PHP, Rails, or another web development platform, that’s fine too.
To get this most out of this book, you’ll need to have a fair level of passion and enthusiasm for your
craft. I hope you’re not satisfied just to throw together any old code that appears at first to work, but
instead would prefer to hone your skills by learning the design patterns, goals, and principles
underpinning ASP.NET MVC. This book frequently compares your architectural options, aspiring to help
you create the highest quality, most robust, simple, and maintainable code possible.

You Don’t Need to Know ASP.NET MVC 1 Already
This book primarily targets developers who are new to ASP.NET MVC; it doesn’t assume any existing
knowledge of ASP.NET MVC 1. Most readers won’t care whether a given feature is new in version 2 or
already existed in version 1, so this book is structured to best teach the whole of ASP.NET MVC 2 in the
most approachable order, not in the order of when each framework feature was first invented.
This is a new edition of a 2009 book about ASP.NET MVC 1. Much of the material is based on the
original book—thoroughly updated and revised, of course, to account for the latest technologies and
developments in industry best practices. If you have already read the previous edition of this book, you
may wish to skim Part 1 of this new book and then go more slowly over the details in Parts 2 and 3.

Which Technologies Are Used in This Book
It doesn’t matter whether you want to work with .NET 3.5 SP1 with Visual Studio 2008 or .NET 4 with
Visual Studio 2010—ASP.NET MVC 2 supports both, so all the code samples and explanations in this

book account for both possibilities. As the primary focus is on .NET 4, readers using .NET 3.5 SP1 will
need to make certain syntactical adjustments that I’ll explain in due course.
All the code samples in this book are written in C#. That’s not because Visual Basic or any other
.NET language is inadequate, but simply because experience shows that C# is by far the most popular
choice among ASP.NET MVC developers. If you’re totally new to C#, you might also like to pick up a copy
of Pro C# 2010 and the .NET 4 Platform, Fifth Edition, by Andrew Troelsen (Apress, 2010).

Code Samples
You can download completed versions of each of the major tutorial applications in this book, plus many
of the more complex code samples shown in other chapters.

xxiii


×