ASP.NET MVC 2 Framework

childlikenumberSecurity

Nov 5, 2013 (3 years and 7 months ago)

1,403 views

Sanderson
SECOND

EDITION
ASP.NET MVC 2
Companion
eBook Available
7.5 x 9.5 spine =1.46875 776 page count
THE EXPERT’S VOICE
®
IN .NET
Pro
ASP.NET MVC 2
Framework
SECOND EDITION
Steven Sanderson
Build the most maintainable, standards-compliant, and best
performing web applications on the Microsoft platform
Pro
this print for content only—size & color not accurate

CYAN

MAGENTA

YELLOW

BLACK

PANTONE 123 C
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
Steven Sanderson,
Author of
Pro ASP.NET MVC
Framework
US $54.99
Shelve in:
.NET
User level:
Intermediate–Advanced
THE APRESS ROADMAP
Pro
Silverlight 4 in C#
Pro
LINQ
Pro
ASP.NET MVC 2
Pro C# 2010
and the
.NET 4 Platform
Pro ASP.NET 4
in C# 2010
Introducing
.NET 4.0
Accelerated
C# 2010
www.apress.com
SOURCE CODE ONLINE
Companion eBook

See last page for details
on $10 eBook version
ISBN 978-1-4302-2886-8
9 781430 228868
55499
Pro ASP.NET MVC 2 Framework
Microsoft’s ASP.NET MVC Framework has dramatically shifted .NET web devel-
opment into the modern age. It promotes maintainability through clean archi-
tecture 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 understand-
ing 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 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
www.free-ebooks-download.org
www.free-ebooks-download.org
i
Pro ASP.NET MVC 2
Framework













■ ■ ■
Steven Sanderson

www.free-ebooks-download.org
ii
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
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 orders-ny@springer-
sbm.com, or visit www.springeronline.com.
For information on translations, please e-mail rights@apress.com, 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.

www.free-ebooks-download.org
iii
To Zoe, who once again loved and supported me throughout this project
www.free-ebooks-download.org
iv
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

v
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
■ CONTENTS
vi
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

■ CONTENTS
vii
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
■ CONTENTS
viii
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

■ CONTENTS
ix
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
■ CONTENTS
x
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

■ CONTENTS
xi
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

■ CONTENTS
xii
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

■ CONTENTS
xiii
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

■ CONTENTS
xiv
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
■ CONTENTS
xv

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
■ CONTENTS
xvi
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
■ CONTENTS
xvii
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

■ CONTENTS
xviii
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

■ CONTENTS
xix
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

■ CONTENTS
xx
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.

■ CONTENTS
xxi
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
stefan.turalski@gmail.com.

■ 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.
■ CONTENTS
xxii
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.


xxiii
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.
■ INTRODUCTION
xxiv
To obtain these files, visit the Apress web site at www.apress.com and search for this book. You can
then download the sample code, which is compressed into a single ZIP file. Code is arranged into
separate directories by chapter. Before using the code, refer to the accompanying readme.txt file for
information about other prerequisites and considerations.
Errata
The author, the technical reviewers, and numerous Apress staff have made every effort to detect and
eliminate all errors from this book’s text and code. However, I’m sure there will still be one or two
glitches in here somewhere! To keep you informed, there’s an errata sheet on the book’s page on
www.apress.com. If you find any errors that haven’t already been reported, such as misspellings or faulty
code, please let us know by e-mailing support@apress.com.
Contacting the Author
You can e-mail me at mvc@stevensanderson.com, or contact me through my blog at
http://blog.stevensanderson.com/. I’ll do my best to reply even if sometimes there’s a bit of a delay
before I can do so!
If you’re looking for general ASP.NET MVC support, then instead please use the product’s online
forum at http://forums.asp.net/1146.aspx.
P A R T 1
■ ■ ■


Introducing ASP.NET
MVC 2
ASP.NET MVC is a radical shift for web developers using the Microsoft platform. It
emphasizes clean architecture, design patterns, and testability, and it doesn’t try to
conceal how the Web works.
The first part of this book is designed to help you understand broadly the
foundational ideas of ASP.NET MVC, including the new features in ASP.NET MVC 2, and
to experience in practice what the framework is like to use.

2
C H A P T E R 1

■ ■ ■

3
What’s the Big Idea?
ASP.NET MVC is a web development framework from Microsoft that combines the effectiveness and
tidiness of model-view-controller (MVC) architecture, the most up-to-date ideas and techniques from
agile development, and the best parts of the existing ASP.NET platform. It’s a complete alternative to
traditional ASP.NET Web Forms, delivering considerable advantages for all but the most trivial of web
development projects.
In this chapter, you’ll learn why Microsoft originally created ASP.NET MVC, how it compares to its
predecessors and alternatives, and finally what’s new in ASP.NET MVC 2.
A Brief History of Web Development
To understand the distinctive aspects and design goals of ASP.NET MVC, it’s worth considering the
history of web development so far—brief though it may be. Among Microsoft’s web development
platforms, we’ve seen over the years an ongoing increase in power and (unfortunately) complexity. As
shown in Table 1–1, each new platform has tackled the specific shortcomings of its predecessor.
Table 1–1. Microsoft’s Lineage of Web Development Technologies
Time Period Technology Strengths Weaknesses
Jurassic
Common Gateway Interface (CGI)
*

Simple
Flexible
Only option at the time
Runs outside the
web server, so is
resource intensive
(spawns separate OS
process per request)
Low-level
Bronze age
Microsoft Internet Database
Connector (IDC)
Runs inside web server
Just a wrapper for
SQL queries and
templates for
formatting result sets
1996 Active Server Pages (ASP) General-purpose
Interpreted at
runtime
Encourages
“spaghetti code”

CHAPTER 1 ■ WHAT’S THE BIG IDEA?
4
Time Period Technology Strengths Weaknesses
2002/03 ASP.NET Web Forms 1.0/1.1 Compiled
“Stateful” UI
Vast infrastructure
Encourages object-
oriented programming
Heavy on bandwidth
Ugly HTML
Untestable

2005 ASP.NET Web Forms 2.0
2007 ASP.NET AJAX
2008 ASP.NET Web Forms 3.5
2009 ASP.NET MVC 1.0 Discussed shortly
2010 ASP.NET MVC 2.0
ASP.NET Web Forms 4.0

* CGI is a standard means of connecting a web server to an arbitrary executable program that returns
dynamic content. Specification maintained by National Center for Supercomputing Applications (NCSA).
In just the same way, ASP.NET MVC 1 was designed to tackle the specific shortcomings of
traditional ASP.NET, but this time by trying to emphasize simplicity.
Traditional ASP.NET Web
Forms
ASP.NET was a huge shift when it first arrived. Figure 1–1 illustrates Microsoft’s new technology stack as
it first appeared in 2002.

Figure 1–1. The ASP.NET Web Forms technology stack
With Web Forms, Microsoft attempted to hide both HTTP (with its intrinsic statelessness) and
HTML (which at the time was unfamiliar to many developers) by modeling a user interface (UI) as a
CHAPTER 1 ■ WHAT’S THE BIG IDEA?
5
server-side hierarchy of control objects. Each control kept track of its own state across requests (using
the ViewState facility), automatically rendered itself as HTML when needed, and automatically connected
client-side events (e.g., a button click) with the corresponding server-side event handler code. In effect,
Web Forms is a giant abstraction layer aimed to deliver a classic event-driven GUI over the Web.
The idea was to make web development feel just the same as Windows Forms development.
Developers no longer had to work with a series of independent HTTP requests and responses, as we did
with earlier technologies; we could now think in terms of a stateful UI. We could forget about the Web,
build UIs using a drag-and-drop designer, and imagine that everything happened on the server.
What’s Wrong with ASP.NET Web Forms?
Traditional ASP.NET Web Forms was a fine idea, and a thrilling prospect at first, but of course reality
turned out to be more complicated. Over the years, real-world use of Web Forms uncovered a range of
weaknesses:
• ViewState weight: The actual mechanism of maintaining state across requests
(ViewState) often results in giant blocks of data being transferred between client
and server. It can reach hundreds of kilobytes in many real-world applications,
and it goes back and forth with every request, frustrating site visitors with a long
wait each time they click a button or try to move to the next page on a grid.
ASP.NET AJAX suffers this just as badly,
1
even though bandwidth-heavy page
updating is one of the main problems that Ajax is supposed to solve.
• Page life cycle: The mechanism of connecting client-side events with server-side
event handler code, part of the page life cycle, can be extraordinarily complicated
and delicate. Few developers have success manipulating the control hierarchy at
runtime without getting ViewState errors or finding that some event handlers
mysteriously fail to execute.
• False sense of separation of concerns: ASP.NET’s code-behind model provides a
means to take application code out of its HTML markup and into a separate code-
behind class. This has been widely applauded for separating logic and
presentation, but in reality developers are encouraged to mix presentation code
(e.g., manipulating the server-side control tree) with their application logic (e.g.,
manipulating database data) in these same monstrous code-behind classes.
Without better separation of concerns, the end result is often fragile and
unintelligible.
• Limited control over HTML: Server controls render themselves as HTML, but not
necessarily the HTML you want. Prior to version 4, their HTML output usually
failed to comply with web standards or make good use of CSS, and server controls
generated unpredictable and complex ID values that are hard to access using
JavaScript. These problems are reduced in ASP.NET 4.



1
It has to send the entire page•s ViewState data back and forth in each asynchronous request.
CHAPTER 1 ■ WHAT’S THE BIG IDEA?
6
• Leaky abstraction: Web Forms tries to hide away HTML and HTTP wherever
possible. While trying to implement custom behaviors, you’ll frequently fall out of
the abstraction, forcing you to reverse-engineer the postback event mechanism or
perform perverse acts to make it generate the desired HTML. Plus, all this
abstraction can act as a frustrating barrier for competent web developers. For
example, rich client-side interactivity is made excessively difficult because all
client-side state can be blown away at any moment by a postback.
• Difficulty applying automated tests: When ASP.NET’s designers first set out their
platform, they could not have anticipated that automated testing would become
the mainstream part of software development that it is today. Not surprisingly, the
tightly coupled architecture they designed is totally unsuitable for unit testing.
Integration testing can be a challenge too, as I’ll explain in a moment.
ASP.NET has kept moving. Version 2.0 added a set of standard application components that can
significantly reduce the amount of code you need to write yourself. The AJAX release in 2007 was
Microsoft’s response to the Web 2.0/Ajax frenzy of the day, supporting rich client-side interactivity while
keeping developers’ lives simple.
2
The most recent 4.0 release makes an effort to produce more
predictable and standards-compliant HTML markup, though it isn’t a radical shift.
Web Development Today
Outside Microsoft, web development technology has been progressing rapidly and in several different
directions since Web Forms was first released. Aside from Ajax, which I’ve already noted, there have
been a few other major developments.
Web Standards and REST
The drive for web standards compliance hasn’t declined in recent years; if anything, it’s increased. Web
sites are consumed on a greater variety of devices and browsers than ever before, and web standards (for
HTML, CSS, JavaScript, etc.) remain our one great hope for getting a decent browsing experience
everywhere—even on the Internet-enabled refrigerator. Modern web platforms cannot afford to ignore
the business case and the weight of developer enthusiasm for web standards compliance.
At the same time, REST
3
has become the dominant architecture for application interoperability over
HTTP, completely overshadowing SOAP (the technology behind ASP.NET’s original approach to Web
Services). Today’s web applications don’t just serve HTML—equally often they must also serve JSON or
XML data to various client technologies including Ajax, Silverlight, and native smartphone applications.
This happens naturally with REST, eliminating the historical distinction between web services and web
applications, but it requires an approach to HTTP and URL handling that has not easily been supported
by ASP.NET Web Forms.



2
Ironically, Microsoft actually invented XMLHttpRequest, the backbone of Ajax technology, to support
Outlook Web Access. However, Microsoft didn’t really capitalize on its potential until hundreds of others
already had.
3
Representational State Transfer (REST) describes an application in terms of resources (URIs)
representing real-world entities and standard operations (HTTP methods) representing available
operations on those resources. For example, you might PUT a new http://www.example.com/
Products/Lawnmower or DELETE http://www.example.com/Customers/Arnold-Smith.
CHAPTER 1 ■ WHAT’S THE BIG IDEA?
7
Agile and Test-Driven Development
It’s not just web development that’s moved on in the last decade—software development as a whole has
experienced a shift toward agile methodologies. This means a lot of different things to different people,
but is largely about running software projects as adaptable processes of discovery, resisting the
encumbrance of excessive bureaucracy and restrictive forward planning. Enthusiasm for agile
methodologies tends to go hand in hand with enthusiasm for a particular set of development practices
and tools—usually open source—that promote and assist such practices.
Test-driven development (TDD), and its latest reincarnation, behavior-driven development (BDD),
are the obvious examples. The idea is to design your software by first describing examples of desired
behaviors (known as tests or specifications), so at any time you can verify your application’s stability and
correctness by executing your suite of specifications against the implementation. There’s no shortage of
.NET tools to support TDD/BDD, but these tend not to work well with Web Forms:
• Unit testing tools let you specify the behavior of individual classes or other small
code units in isolation. These can only be applied effectively to software that’s
designed as a set of cleanly separated, independent modules, so each can run in
isolation. Unfortunately, very few Web Forms applications can be described in
this way; following the framework’s guidance to put logic into event handlers or
even use server controls that directly query databases, developers typically end up
tightly coupling their own application logic to the Web Forms runtime
environment. This is death for unit testing.
• UI automation tools let you simulate a series of user interactions against a
complete running instance of your application. These can in theory be used with
Web Forms, but they can break down whenever you make a slight change to your
page layout. Without special attention, Web Forms starts generating totally
different HTML structures and element IDs, rendering your existing test suite
useless.
The .NET open source and independent software vendor (ISV) community has produced no end of
top-quality unit testing frameworks (NUnit, xUnit), mocking frameworks (Moq, Rhino Mocks),
inversion-of-control containers (Ninject, AutoFac), continuous integration servers (Cruise Control,
TeamCity), object-relational mappers (NHibernate, Subsonic), and the like; and proponents of these
tools and techniques have even found a common voice, publishing and organizing conferences under
the shared brand ALT.NET. Traditional ASP.NET Web Forms is not very amenable to these tools and
techniques because of its monolithic design, so from this vocal group of experts and industry thought
leaders, Web Forms gets little respect.
Ruby on Rails
In 2004, Ruby on Rails was a quiet, open source contribution from an unknown player. Suddenly it hit
fame, transforming the rules of web development. It’s not so much that it contained revolutionary
technology, but more that it took existing ingredients and blended them in such a wonderful, magical,
delicious way as to put existing platforms to shame.
By applying MVC architecture (an old pattern that many web frameworks have recently
rediscovered), by working in tune with the HTTP protocol instead of against it, by promoting
conventions instead of the need for configuration, and by integrating an object-relational mapping
(ORM) tool into its core, Rails applications more or less fell into place without much expense of effort. It
was as if this was how web development should have been all along; as if we’d suddenly realized we’d
been fighting our tools all these years, but now the war was over.
CHAPTER 1 ■ WHAT’S THE BIG IDEA?
8
Rails shows that web standards compliance and RESTfulness don’t have to be hard. It also shows