proasp.net mvc 2 framework · 2010. 9. 22. · proasp.netmvc2 framework second edition ......

16
Pro ASP.NET MVC 2 Framework Second Edition Steven Sanderson Apress® TIB/UB Hannover 89 133 297 713

Upload: others

Post on 26-Sep-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

Pro ASP.NET MVC 2

FrameworkSecond Edition

Steven Sanderson

Apress®

TIB/UB Hannover 89

133 297 713

Page 2: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

Contents at a Glance

Contents

About the Author

About the Technical Reviewers

AcknowledgmentsIntroduction xxiu

Part 1: Introducing ASP.NET MVC 2

Chapter 1: What's the Big Idea?

A Brief History of Web Development

Traditional ASP.NET Web Forms

What's Wrong with ASP.NET Web Forms?

Web Development Today

Web Standards and REST

Agile and Test-Driven Development

Ruby on Rails

Key Benefits of ASP.NET MVC

MVC Architecture

Extensibility

Tight Control over HTML and HTTP

Testability

Powerful Routing System

Built on the Best Parts of the ASP.NET Platform

Page 3: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

m 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 Ul (Anti-Pattern) 44

Separating Out the Domain Model 45

vi

Page 4: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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 Dl 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

Page 5: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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 Dl 109

Creating a Custom Controller Factory 109

Using Your Dl 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

Page 6: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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 Dl Component 169

Completing CartController 169

Implementing EmailOrderSuhmitter , 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

Page 7: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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

Page 8: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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

Page 9: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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

Page 10: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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

Page 11: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

MCONTENTS

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

Page 12: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

mCONTENTS

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

Page 13: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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 Ul's Prebuilt Ul 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

Page 14: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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

Page 15: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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

Page 16: ProASP.NET MVC 2 Framework · 2010. 9. 22. · ProASP.NETMVC2 Framework Second Edition ... TheSmartUl (Anti-Pattern) 44 SeparatingOuttheDomainModel 45 vi. CONTENTS Three-TierArchitecture

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