ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web...

22
ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

Transcript of ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web...

Page 1: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

ASP.NET Web API 2: Building a REST Service

from Start to Finish

Jamie Kurtz

Brian Wortman

Page 2: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

ASP.NET Web API 2: Building a REST Service from Start to Finish

Copyright © 2014 by Jamie Kurtz and Brian Wortman

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law.

ISBN-13 (pbk): 978-1-4842-0110-7

ISBN-13 (electronic): 978-1-4842-0109-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.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

Publisher: Heinz WeinheimerLead Editor: James DeWolfDevelopment Editor: Douglas PundickTechnical Reviewer: Fabio FerracchiatiEditorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan, Jim DeWolf,

Jonathan Gennick, Jonathan Hassell, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Steve Weiss

Coordinating Editor: Kevin WalterCopy Editor: Roger LeBlancCompositor: SPi GlobalIndexer: SPi GlobalArtist: SPi GlobalCover Designer: Anna Ishchenko

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

For information on translations, please e-mail [email protected], 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/bulk-sales.

Any source code or other supplementary material referenced by the author in this text is available to readers at www.apress.com. For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/.

Page 3: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

I would like to dedicate this book to my loving wife and beautiful daughters, whose patience and grace for time spent on yet another book made all the difference in the world.

—Jamie

To Him who was, and is, and is to come.

—Brian

Page 4: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman
Page 5: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

v

Contents at a Glance

About the Authors ��������������������������������������������������������������������������������������������������������������xiii

About the Technical Reviewer �������������������������������������������������������������������������������������������� xv

Acknowledgments ������������������������������������������������������������������������������������������������������������ xvii

Foreword ��������������������������������������������������������������������������������������������������������������������������� xix

Introduction ����������������������������������������������������������������������������������������������������������������������� xxi

Chapter 1: ASP�NET as a Service Framework ■ ��������������������������������������������������������������������1

Chapter 2: What Is RESTful? ■ ����������������������������������������������������������������������������������������������9

Chapter 3: Designing the Sample REST API ■ ���������������������������������������������������������������������21

Chapter 4: Building the Environment and Creating the Source Tree ■ �������������������������������31

Chapter 5: Up and Down the Stack with a POST ■ ��������������������������������������������������������������49

Chapter 6: Securing the Service ■ ������������������������������������������������������������������������������������117

Chapter 7: Dealing with Relationships, Partial Updates, and Other Complexities ■ ���������157

Chapter 8: Supporting Diverse Clients ■ ���������������������������������������������������������������������������209

Chapter 9: Completing the Picture ■ ��������������������������������������������������������������������������������221

Index ���������������������������������������������������������������������������������������������������������������������������������251

Page 6: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman
Page 7: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

vii

Contents

About the Authors ��������������������������������������������������������������������������������������������������������������xiii

About the Technical Reviewer �������������������������������������������������������������������������������������������� xv

Acknowledgments ������������������������������������������������������������������������������������������������������������ xvii

Foreword ��������������������������������������������������������������������������������������������������������������������������� xix

Introduction ����������������������������������������������������������������������������������������������������������������������� xxi

Chapter 1: ASP�NET as a Service Framework ■ ��������������������������������������������������������������������1

In the Land of JavaScript and Mobile Devices ������������������������������������������������������������������������������2

Advantages of Using the ASP�NET Web API ������������������������������������������������������������������������������������2

Configuration ��������������������������������������������������������������������������������������������������������������������������������������������������������� 2

REST by Default ����������������������������������������������������������������������������������������������������������������������������������������������������� 2

Abstraction with Routes ���������������������������������������������������������������������������������������������������������������������������������������� 5

Controller Activation Is, Well, Very Nice ����������������������������������������������������������������������������������������������������������������� 5

Simpler Extensible Processing Pipeline ���������������������������������������������������������������������������������������������������������������� 5

Interoperability of JSON, XML, and REST ��������������������������������������������������������������������������������������������������������������� 6

A Few Feature Highlights of the ASP�NET Web API ������������������������������������������������������������������������6

Summary ���������������������������������������������������������������������������������������������������������������������������������������7

Chapter 2: What Is RESTful? ■ ����������������������������������������������������������������������������������������������9

From RPC to REST �������������������������������������������������������������������������������������������������������������������������9

XML-RPC and SOAP ��������������������������������������������������������������������������������������������������������������������������������������������� 10

URIs and Resources ��������������������������������������������������������������������������������������������������������������������������������������������� 12

HTTP Verbs ���������������������������������������������������������������������������������������������������������������������������������������������������������� 12

HATEOAS �������������������������������������������������������������������������������������������������������������������������������������������������������������� 14

Page 8: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

■ Contents

viii

HTTP Status Codes ����������������������������������������������������������������������������������������������������������������������17

HAL, Collection+JSON, … �����������������������������������������������������������������������������������������������������������19

Summary �������������������������������������������������������������������������������������������������������������������������������������19

Chapter 3: Designing the Sample REST API ■ ���������������������������������������������������������������������21

Task Management Resource Types ���������������������������������������������������������������������������������������������21

Hypermedia Links ������������������������������������������������������������������������������������������������������������������������������������������������ 22

Modeling the URIs and HTTP Verbs ���������������������������������������������������������������������������������������������������������������������� 24

The Task-Management Data Model ���������������������������������������������������������������������������������������������27

Choosing Architecture Components ��������������������������������������������������������������������������������������������28

Data Access ��������������������������������������������������������������������������������������������������������������������������������������������������������� 28

Type Mapper �������������������������������������������������������������������������������������������������������������������������������������������������������� 28

IoC Container ������������������������������������������������������������������������������������������������������������������������������������������������������� 29

Logger������������������������������������������������������������������������������������������������������������������������������������������������������������������ 29

Testing Framework ���������������������������������������������������������������������������������������������������������������������������������������������� 29

Mocking Framework �������������������������������������������������������������������������������������������������������������������������������������������� 29

Summary �������������������������������������������������������������������������������������������������������������������������������������29

Chapter 4: Building the Environment and Creating the Source Tree ■ �������������������������������31

Configuring the Machine �������������������������������������������������������������������������������������������������������������31

Windows 8 64-bit with �NET Framework 4�51 ����������������������������������������������������������������������������������������������������� 31

SQL Server 2012 �������������������������������������������������������������������������������������������������������������������������������������������������� 32

Visual Studio 2013 ����������������������������������������������������������������������������������������������������������������������������������������������� 32

NuGet Package Manager 2�6 ������������������������������������������������������������������������������������������������������������������������������� 32

Creating the Folder Structure ������������������������������������������������������������������������������������������������������33

Creating the Solution �������������������������������������������������������������������������������������������������������������������34

NuGet Config File �������������������������������������������������������������������������������������������������������������������������35

Adding the Projects ���������������������������������������������������������������������������������������������������������������������35

Basic Components �����������������������������������������������������������������������������������������������������������������������40

Domain Model ������������������������������������������������������������������������������������������������������������������������������������������������������ 40

Service Model Types �������������������������������������������������������������������������������������������������������������������������������������������� 41

Page 9: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

■ Contents

ix

Logging ���������������������������������������������������������������������������������������������������������������������������������������������������������������� 43

The Database ������������������������������������������������������������������������������������������������������������������������������������������������������� 44

Summary �������������������������������������������������������������������������������������������������������������������������������������47

Chapter 5: Up and Down the Stack with a POST ■ ��������������������������������������������������������������49

Routing ����������������������������������������������������������������������������������������������������������������������������������������50

Adding an HttpRequestMessage Argument ��������������������������������������������������������������������������������������������������������� 52

Adding a Model Object Argument ������������������������������������������������������������������������������������������������������������������������ 52

Attribute-Based Routing �������������������������������������������������������������������������������������������������������������������������������������� 52

Versioning �����������������������������������������������������������������������������������������������������������������������������������57

Implementing POST ��������������������������������������������������������������������������������������������������������������������������������������������� 58

Dependencies ������������������������������������������������������������������������������������������������������������������������������68

Constructor Injection of Dependencies ���������������������������������������������������������������������������������������������������������������� 69

Configuring Ninject Dependency Injection ����������������������������������������������������������������������������������������������������������� 69

Container Configuration ��������������������������������������������������������������������������������������������������������������������������������������� 70

Container Bindings ���������������������������������������������������������������������������������������������������������������������������������������������� 70

IDependencyResolver for Ninject ������������������������������������������������������������������������������������������������������������������������� 73

Completing NinjectWebCommon ������������������������������������������������������������������������������������������������������������������������� 74

NHibernate Configuration and Mappings ������������������������������������������������������������������������������������76

Database Configuration: Overview ���������������������������������������������������������������������������������������������������������������������� 76

Adding Concurrency Support to Entities �������������������������������������������������������������������������������������������������������������� 77

Entity Mapping ����������������������������������������������������������������������������������������������������������������������������������������������������� 77

Mapping Relationships ���������������������������������������������������������������������������������������������������������������������������������������� 80

Database Configuration: Bringing It All Together ������������������������������������������������������������������������������������������������� 80

Managing the Unit of Work ����������������������������������������������������������������������������������������������������������82

Database Transaction Control ������������������������������������������������������������������������������������������������������87

Diagnostic Tracing �����������������������������������������������������������������������������������������������������������������������88

Error Handling �����������������������������������������������������������������������������������������������������������������������������90

Page 10: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

■ Contents

x

Persisting a Task and Returning IHttpActionResult ���������������������������������������������������������������������95

New Service Model Type ������������������������������������������������������������������������������������������������������������������������������������� 95

Persisting the Task ���������������������������������������������������������������������������������������������������������������������������������������������� 97

IHttpActionResult ����������������������������������������������������������������������������������������������������������������������������������������������� 110

Summary �����������������������������������������������������������������������������������������������������������������������������������114

Chapter 6: Securing the Service ■ ������������������������������������������������������������������������������������117

The Main Idea ����������������������������������������������������������������������������������������������������������������������������117

Authentication ��������������������������������������������������������������������������������������������������������������������������������������������������� 118

Authorization ����������������������������������������������������������������������������������������������������������������������������������������������������� 119

Overview of the Authentication and Authorization Process ������������������������������������������������������������������������������� 120

Securing the POST ��������������������������������������������������������������������������������������������������������������������120

The Authorization Filter�������������������������������������������������������������������������������������������������������������������������������������� 120

A Message Handler to Support HTTP Basic Authentication ������������������������������������������������������������������������������� 121

Securing Non-Resource API Operations ������������������������������������������������������������������������������������129

Activate a Task ��������������������������������������������������������������������������������������������������������������������������������������������������� 129

Complete a Task ������������������������������������������������������������������������������������������������������������������������������������������������ 135

Reactivate a Task ����������������������������������������������������������������������������������������������������������������������������������������������� 138

Auditing ������������������������������������������������������������������������������������������������������������������������������������������������������������� 141

GET a Task ���������������������������������������������������������������������������������������������������������������������������������144

Applying Token-Based Security �������������������������������������������������������������������������������������������������150

Token Basics ������������������������������������������������������������������������������������������������������������������������������������������������������ 150

The JSON Web Token ����������������������������������������������������������������������������������������������������������������������������������������� 151

Configuring the JwtAuthForWebAPI Package ���������������������������������������������������������������������������������������������������� 151

Getting a Task Using a JWT ������������������������������������������������������������������������������������������������������������������������������� 153

SSL, XSS, CORS, and CSRF ��������������������������������������������������������������������������������������������������������155

Summary �����������������������������������������������������������������������������������������������������������������������������������155

Chapter 7: Dealing with Relationships, Partial Updates, and Other Complexities ■ ���������157

Task and User Relationships �����������������������������������������������������������������������������������������������������157

Partial Update of a Task Using PUT/PATCH ��������������������������������������������������������������������������������166

Page 11: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

■ Contents

xi

Validation Using an Action Filter ������������������������������������������������������������������������������������������������174

Specialized Action Filter to Validate Task Updates �������������������������������������������������������������������������������������������� 175

Generalized Action Filter to Validate New Tasks ������������������������������������������������������������������������������������������������ 178

Paging of Results ����������������������������������������������������������������������������������������������������������������������181

Constructing the Filter with a Data Request Factory ����������������������������������������������������������������������������������������� 181

Filtering the Results������������������������������������������������������������������������������������������������������������������������������������������� 185

Hypermedia Links����������������������������������������������������������������������������������������������������������������������195

Common Link Service ���������������������������������������������������������������������������������������������������������������������������������������� 195

Business Domain-Specific Link Services ���������������������������������������������������������������������������������������������������������� 200

Putting It Together ��������������������������������������������������������������������������������������������������������������������������������������������� 203

Summary �����������������������������������������������������������������������������������������������������������������������������������207

Chapter 8: Supporting Diverse Clients ■ ���������������������������������������������������������������������������209

Project Requirements ����������������������������������������������������������������������������������������������������������������209

Content Negotiation �������������������������������������������������������������������������������������������������������������������210

Supporting SOAP-Based Clients ������������������������������������������������������������������������������������������������212

Where Is the Controller? ������������������������������������������������������������������������������������������������������������������������������������ 213

Configuring the Route ���������������������������������������������������������������������������������������������������������������������������������������� 216

Adding a Custom Formatter ������������������������������������������������������������������������������������������������������������������������������� 217

Summary �����������������������������������������������������������������������������������������������������������������������������������220

Chapter 9: Completing the Picture ■ ��������������������������������������������������������������������������������221

Testing the API ���������������������������������������������������������������������������������������������������������������������������221

Unit Testing �������������������������������������������������������������������������������������������������������������������������������������������������������� 222

Integration Testing ��������������������������������������������������������������������������������������������������������������������������������������������� 241

Going Live! ��������������������������������������������������������������������������������������������������������������������������������243

Logging In ���������������������������������������������������������������������������������������������������������������������������������������������������������� 244

Support for CORS ����������������������������������������������������������������������������������������������������������������������������������������������� 248

Summary �����������������������������������������������������������������������������������������������������������������������������������250

Index ���������������������������������������������������������������������������������������������������������������������������������251

Page 12: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman
Page 13: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

xiii

About the Authors

Jamie Kurtz has over 17 years of experience working in a variety of roles as engineer and solution provider. While working as a developer and tester for an education software company, and working as a developer in a high-temperature super conductivity lab, he received his Bachelor of Science from Western Michigan University—double majoring in Physics and Mathematics and minoring in Computer Science.

From there, Jamie worked in DBA, project lead, team lead, manager, architect, advisor, tester, and developer roles in various industries, including: telecommunications, fulfillment, manufacturing, banking, and video intelligence/security. He is currently working as consultant and group manager at Fusion Alliance, Inc. in Indianapolis, Indiana.

In addition to love and enjoyment of his beautiful wife and two daughters (and dog and cat), and great times playing drums at an awesome local church, Jamie continually seeks opportunities to share his passion for helping software teams build and deliver real value to their customers.

Brian Wortman has been developing software for more than 20 years across a wide range of industries, including pharmaceutical, healthcare, telecommunications, surveillance, military, and financial. He received an M.S. in Computer Science from Johns Hopkins University in 1998. He is currently working as a senior consultant at Fusion Alliance, Inc. in Indianapolis, Indiana.

In addition to technology, Brian’s interests include religion, politics, music, cars, and real estate. He has too many hobbies to mention (and to excel at any particular one), but most of them involve The Great Outdoors in one way or another. Yes, he even enjoys yard work!

Last but not least, Brian is a member of Christ Covenant Orthodox Presbyterian Church in Sheridan, Indiana, where he worships the Lord with his wife of 22 years (and counting) and his wonderful daughters, Jan and Danielle.

Page 14: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman
Page 15: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

xv

About the Technical Reviewer

Fabio Claudio Ferracchiati is a senior consultant and a senior analyst/developer using Microsoft technologies. He works at BluArancio SpA (www.bluarancio.com) as Senior Analyst/Developer and Microsoft Dynamics CRM Specialist. He is a Microsoft Certified Solution Developer for .NET, a Microsoft Certified Application Developer for .NET, a Microsoft Certified Professional, and a prolific author and technical reviewer. Over the past ten years, he’s written articles for Italian and international magazines and coauthored more than ten books on a variety of computer topics.

Page 16: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman
Page 17: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

xvii

Acknowledgments

We’d like to thank you, our reader. Without you, there wouldn’t have been much point in writing this book! We look forward to learning from your comments and constructive criticisms. We are firm believers in the Agile way, which at its heart is all about feedback. Please feel free to share yours.

We’d like to thank Kevin Walter, Douglas Pundick, Roger LeBlanc, Jim DeWolf, and Fabio Claudio Ferracchiati of the Apress team. It was a pleasure to work with such a talented and encouraging group of individuals. Their input and efforts toward getting this book to market were invaluable.

For a similar reason, we’d like to thank our friends and colleagues Glenn Orr, Ray Clanan, and Jim Kelly. Though not part of the official editing team, these guys contributed their keen technical skills to help make sure the material contained herein is accessible and accurate.

I (Jamie) would also like to thank Brian Wortman for continuing to push me into excellence. Most people don’t realize that Brian and I approach software very differently. I like to go fast and furious, seeking adventure and excitement along the way, growing bored quickly, usually skirting the details and finishing touches. Brian tackles every project with the application of tried-and-true patterns and practices, never stopping short of pure excellence, and never growing tired of the daily rigors that make up most of software development. He is truly the image of discipline. Without his (sometimes forceful) influence, I wouldn’t have ever taken the time to learn so much of what makes me the developer I am today. Brian pushed me, kicking and screaming, into unit tests, design patterns, clean code, refactoring, and taking the time to complete with excellence that last 10% of a project that we all hate. So thanks a ton, Brian.

I (Brian) would like to thank my longtime friend (and boss) Jamie Kurtz for giving me the opportunity to coauthor this book. Yes, it was a lot of work . . . and yes, we’re still friends (and I think I still have a job)! I’d also like to thank my pastor (Mark Melton), my friends, and my family for their prayers and encouragement. I’d especially like to thank my loving wife, Yvonne, and my precious daughters, Jan and Danielle. They are a constant reminder of how richly blessed I am.

Page 18: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman
Page 19: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

xix

Foreword

It’s the end of the project. Project managers are happy, you’ve released the code on time, and it even works! Everyone is congratulating you for a job well done, but every pat on the back is like a lash from the whip of guilt. You harbor a dark secret that will soon be found out—your code. At first everything was great. You got to start from scratch, and hey, you even got to use a new framework! Then you built the code base, fixed bugs, and added features that were missed in the requirements document. But so many unexpected changes turned the code base into a tangled mess. It started new and shiny, but it ended as a crufty disaster. It works, but man, if you only had it to do all over again.

We all know that special sort of coding pain where you have this sense of accomplishment laced with frustration and guilt. Even worse, it’s New Code 2.0! People are happy with it, and it may even end up as the core of many more projects to come. Too many projects and code bases start off with the guilt-laced code described. Every developer wants to rewrite it in a vain effort to erase their embarrassment from history and in the end make it right.

This book isn’t about making it right. This book is about starting it right, written by brilliant and talented developers with many years of experience. The authors guide you through creating a REST API from start to finish. They cover SOLID principles, security, patterns, unit tests, integration tests, and backward compatibility for those clients that just can’t understand that sometimes it is OK to drop the SOAP.

The authors, Jamie and Brian, will guide you through the entire process of designing and implementing a RESTful service—explaining what ASP.NET Web API 2 is, and what REST is and is not. They take you through the process of designing a task-management API and setting up the Visual Studio project. From there they show you how to implement the API, security, SOAP support, unit and integration tests, and then finally, a quick SPA web page to consume the service.

I hope you enjoy this book as much as I have. Usually technology books are very light on concept and more about demonstrating the technology at hand. To get information on clean code, you have to read a more abstract book and then spend a while experimenting to figure out how to correctly implement the idea with the technology. This process is usually shortened by having a developer experienced in the process on hand to help guide the project. This book is very similar to having that developer on hand, which I found very useful. Some concepts I formerly struggled to understand clicked, and overall I came out understanding not only ASP.NET Web API, or what a REST web service is, but also how to make a clean design overall and how to apply various SOLID concepts. I hope it does the same for you.

—Jim KellyFusion Alliance, Inc.

Indianapolis, Indiana

Page 20: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman
Page 21: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

xxi

Introduction

With the introduction of services technology over a decade ago, Microsoft made it relatively easy to build and support web services with the .NET Framework. Starting with XML Web Services, and then adding the broadly capable Windows Communication Foundation (WCF) several years later, Microsoft gave .NET developers many options for building SOAP-based services. With some basic configuration changes, you could support a wide array of communication protocols, authentication schemes, message formats, and WS-* standards with WCF. But as the world of connected devices evolved, the need arose within the community for a simple HTTP-only services framework—without all of the capabilities (and complexity) of WCF. Developers realized that most of their newer services did not require federated authentication or message encryption, nor did they require transactions or Web Services Description Language (WSDL)–based discovery. And the services really only needed to communicate over HTTP, not named pipes or MSMQ.

In short, the demand for mobile-to-service communication and browser-based, single-page applications started increasing exponentially. It was no longer just large enterprise services talking SOAP/RPC to each other. Now a developer needed to be able to whip up a JavaScript application, or 99-cent mobile app, in a matter of days—and those applications needed a simple HTTP-only, JSON-compatible back end. The Internet needs of these applications looked more and more like Roy Fielding’s vision of connected systems (i.e., REST).

And so Microsoft responded by creating the ASP.NET Web API, a super-simple yet very powerful framework for building HTTP-only, JSON-by-default web services without all the fuss of WCF. Model binding works out of the box, and returning Plain Old CLR Objects is drop-dead easy. Configuration is available (though almost completely unnecessary), and you can spin up a RESTful service in a matter of minutes.

The previous edition of this book, ASP.NET MVC 4 and the Web API: Building a REST Service from Start to Finish, spent a couple chapters describing REST and then dove into building a sample service with the first version of ASP.NET Web API. In a little over a hundred pages, you were guided through the process of implementing a working service. But based on reader feedback, I discovered that a better job needed to be done in two major areas: fewer opinions about patterns and best practices and various open source libraries, and more details on the ASP.NET Web API itself. So when the second version of the ASP.NET Web API was released, Brian Wortman and I decided it was time to release a version 2 of the book. Brian wanted to help me correct some glaring “bugs,” and also incorporate some great new features found in ASP.NET Web API 2. And so this book was born.

In this second edition, we will cover all major features and capabilities of the ASP.NET Web API (version 2). We also show you how to support API versioning, input validation, non-resource APIs, legacy/SOAP clients (this is super cool!), partial updates with PATCH, adding hypermedia links to responses, and securing your service with OAuth-compatible JSON Web Tokens. Improving upon the book’s first edition, we continue to evolve the message and techniques around REST principles, controller activation, dependency injection, database connection and transaction management, and error handling. While we continue to leverage certain open source NuGet packages, we have eliminated the chatter and opinions around those choices. We also spend more time on the code—lots of code. Unit tests and all. And in the end, we build a simple KnockoutJS-based Single Page Application (SPA) that demonstrates both JSON Web Token authentication and use of our new service.

Page 22: ASP.NET Web API 2: Building a REST Service from Start to ...978-1-4842-0109-1/1.pdf · ASP.NET Web API 2: Building a REST Service from Start to Finish Jamie Kurtz Brian Wortman

■ IntroduCtIon

xxii

We have also made improvements in response to your feedback regarding the source code that accompanied the first book. Therefore, on GitHub you will find a git repository containing all of the code for the task-management service we will build together (https://github.com/jamiekurtz/WebAPI2Book). The repository contains one branch per chapter, with multiple check-ins (or “commits”) per branch to help guide you step-by-step through the implementation. The repository also includes a branch containing the completed task-management service, with additional code to help reinforce the concepts that we cover in the book. Of course, feel free to use any of this code in your own projects.

I am very excited about this book. Both Brian and I are firm believers in the “Agile way,” which at its heart is all about feedback. So we carefully triaged each and every comment I received from the first book and did our best to make associated improvements. And I’m really excited about all the new features in the second version of ASP.NET Web API. So many capabilities have been added, but Microsoft has managed to maintain the framework’s simplicity and ease of use.

We hope you not only find this book useful in your daily developer lives, but also find it a pleasure to read. As always, please share any feedback you have. We not only love to hear it, but your feedback is key in making continuous improvements.

Cheers,—Jamie Kurtz

(Brian Wortman)