Library of Congress Cataloging-in-Publication...

65

Transcript of Library of Congress Cataloging-in-Publication...

Page 1: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,
Page 2: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Many of the designations used by manufacturers and sellers to distinguish their products areclaimed as trademarks. Where those designations appear in this book, and the publisher wasaware of a trademark claim, the designations have been printed with initial capital letters orin all capitals.

The .NET_logo is either a registered trademark or trademark of Microsoft Corporation in theUnited States and/or other countries and is used under license from Microsoft.

Microsoft, Windows, Visual Basic, Visual C#, and Visual C++ are either registered trademarksor trademarks of Microsoft Corporation in the U.S.A. and/or other countries/regions.

The authors and publisher have taken care in the preparation of this book, but make noexpressed or implied warranty of any kind and assume no responsibility for errors oromissions. No liability is assumed for incidental or consequential damages in connectionwith or arising out of the use of the information or programs contained herein.

The publisher offers excellent discounts on this book when ordered in quantity for bulkpurchases or special sales, which may include electronic versions and/or custom covers andcontent particular to your business, training goals, marketing focus, and branding interests.For more information, please contact:

U.S. Corporate and Government Sales(800) [email protected]

For sales outside the United States please contact:

International [email protected]

Visit us on the Web: informit.com/aw

Library of Congress Cataloging-in-Publication Data:

Scribner, Kenn.Effective REST services via .NET : for .NET Framework 3.5 / Kenn Scribner, Scott Seely.

p. cm.ISBN-13: 978-0-321-61325-7 (pbk. : alk. paper)ISBN-10: 0-321-61325-2 (pbk. : alk. paper) 1. Web services. 2. Representational state

transfer (Software architecture) 3. Web site development. 4. Internet programming. 5.Microsoft .NET Framework. I. Seely, Scott, 1972- II. Title. TK5105.88813.S32 2009006.7’882—dc22

2009002859

Copyright © 2009 Pearson Education, Inc.

All rights reserved. Printed in the United States of America. This publication is protected bycopyright, and permission must be obtained from the publisher prior to any prohibitedreproduction, storage in a retrieval system, or transmission in any form or by any means,electronic, mechanical, photocopying, recording, or likewise. For information regardingpermissions, write to:

Pearson Education, IncRights and Contracts Department501 Boylston Street, Suite 900Boston, MA 02116Fax (617) 671-3447

ISBN-13: 978-0-321-61325-7ISBN-10: 0-321-61325-2

Text printed in the United States on recycled paper at Courier in Westford, Massachusetts.First printing April 2009

Page 3: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Foreword

SOAP has been with us for the better part of ten years now, but few wouldargue that it has lived up to its promise. It works, and it has been used totie together thousands of services and service consumers. But if youbelieve simpler is better, SOAP falls short. XML is verbose, WS-* is com-plex, and interoperability is elusive. SOAP may be the right tool for the jobwhen it comes to composing an SOA symphony from disparate enterpriseservers, but for the vast majority of today’s consumer-oriented applica-tions, SOAP is not only overkill, it’s too slow and too complex to merithonest consideration.

Enter REST. Fast becoming the most important Web service protocol onthe planet, REST is everything SOAP isn’t. Want to dress up an applicationwith real-time weather data? How about firing off an HTTP request tohttp://www.contoso.com/weather/98052 and parsing a few bytes ofXML returned in the response? You don’t need elaborate tooling supportto consume WSDL contracts and generate Web Service proxies, nor do youneed SOAP libraries to generate and digest hundreds of lines of messageheaders. A few lines of code and an XML parser will do. Moreover, youmight not even need the parser; REST services can return data in any for-mat they want. With REST, the wire format is driven by the requirementsof the application, not by the protocol that the application uses.

This is why the world seems to have settled on REST as the simplestand most effective means for publishing data and services to consumer-oriented applications. Flickr exposes a REST API for searching its massivestore of photographs; Amazon offers a REST API for searching its product

xix

Page 4: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

catalog; Google and Yahoo provide REST APIs for search, traffic data, geo-graphical data, and more; and Digg makes news stories, videos, and moreavailable via REST. The list could go on and on, but the upshot is thatREST is the language spoken by the most “interesting” public-facing serv-ices today and is likely to be used to expose even more interesting stuff inthe future. When you publish data the REST way, you’re in good company.And understanding REST is the key to building content-rich applicationsthat draw from resources outside your own application domain. You prob-ably don’t have access to your own Doppler weather radar, but somebodyelse does—and if they’re willing to share that information through REST,then you, too, can incorporate real-time weather data into your UI.

Microsoft’s Web stack offers a number of ways for developers to buildRESTful services. You can implement them using IIS, ASP.NET, ASP.NET’sMVC framework, WCF, and even Azure and .NET Services. Under-standing the programming models is a key first step in architecting andimplementing REST services and clients. Should you author services usingWCF or ASP.NET? Should data be encoded as XML or JSON? Whichmodel delivers the best balance of performance and ease of implementa-tion, which one provides the best support for unit testing, and whatshould I know about best practices before I start?

I can’t think of anyone better or more qualified to answer these ques-tions than Kenn Scribner and Scott Seely. I’ve had the privilege of workingwith both of them in recent years, and besides being passionate about thesubject, both are world-class presenters with a knack for breaking downcomplex information and presenting it in understandable, bite-sizedchunks. Both have real-world experience building Web Services and WebService clients on Microsoft platforms. And both possess the perspectiveneeded to present a fair and balanced view of REST development, sharingwith you not only the hows but the whys—and in some cases, thewhy-nots.

I can’t promise you that REST won’t be displaced in a year or two bysomething sexier. In fact, I can guarantee that it will be replaced someday,perhaps sooner rather than later; such is the nature of our industry. But forthe time being, REST is where the action is, and becoming REST-literate is

Forewordxx

Page 5: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

one of the smartest things a developer can do to sharpen his or her skillset. Join Kenn and Scott as they take you on a RESTful journey through theMicrosoft technology stack; and most of all, sit back and enjoy the ride!

Jeff ProsiseKnoxville, TNFebruary 2009

Foreword xxi

Page 6: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Preface

Kenn’s Thoughts: The Road to REST, an Engineer’s Tale

It was the spring of 2008, and I had just completed some work for JustinSmith, a senior engineer and connected systems expert at Microsoft. Thework involved developing two related Web sites that would consumeservices offered by a third Web application that would be hosted in some-thing known as the “cloud.” After six weeks of iterative development, wehad a set of Web applications that were designed to demonstrate nearly allthe ways Web applications can communicate using .NET technologies.

I’d heard about REST, of course, having been fortunate enough to workwith Dino Esposito on several of his ASP.NET and AJAX books. Dino is ahuge REST proponent. But I admit my background was more along thelines of the SOAP protocol, and I looked at Web services more as remotemethod calls than creatures of the Internet ecosystem. It didn’t bother methat I needed fancy proxies to communicate with XML-based (and notJSON-based) Web services. I truly hadn’t consciously considered thenotion that remote procedure call (RPC) style messaging wasn’t quitearchitecturally in harmony with the Internet itself.

But I’d had this nagging concern for some time. SOAP and XML-RPCservices were becoming very complex, and it seemed that at every turn wewere trying to solve some problem that the basic architecture of theInternet presented. Security, streaming large binary objects, browser-basedproxies (for AJAX), and so forth were leading to an ever-increasing

xxiii

Page 7: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

number of new specifications, each designed to layer more complexity onto what had started as a simple concept. And in most cases, we were try-ing to bypass the basic workings of the Internet rather than using them toour advantage.

After working with Justin, and after building a very detailed and fullyfunctional set of Web applications that were primarily based on RESTfulprinciples, I found I had drunk from the RESTful Kool-Aid pitcher, and Iwas stunned by what I had overlooked all of these years. I can rememberthe epiphany…I literally sat up in my chair, stunned by what I hadrealized.

What I had overlooked was the simplicity and elegance of the Web’sarchitecture and design. I had been overcome by the glamour of XML andserializing binary information for transmission in response to requests foractions. I had lost sight of the Internet’s most basic capability of asking forand receiving a resource’s representation. The simplicity and elegance ofthe Internet struck a new chord with me that day. Even though I had beenworking with Internet-based technologies for nearly ten years, I found I’dsuddenly rediscovered programming for the Internet.

And the simple truth is this is not a bad thing, nor is it uncommon. RESTas an architectural concept is precisely in line with the architecture of theWeb itself. Any tool you have that can build Web applications can be usedto build RESTful services. If you have access to the HTTP method—���,����, and so forth—and if you have access to the HTTP headers and entitybody, you have all you need to create a RESTful service. Anything else isthere only to make creating RESTful services easier by hiding some of thedetail. I haven’t had the pleasure of meeting Dr. Roy Fielding, but based onhis doctoral dissertation that introduces us all to the concept of REST, I’dhazard a guess that he’d prefer you understand REST at its lowest levelbefore using frameworks that mask the underpinnings. When you do,REST makes perfect sense and things become very clear. Or at least I felt so.

Scott’s Thoughts: REST Is Best

From 2000 until the middle of 2006, I worked at Microsoft on Web serv-ices. For four of those years, I worked on Windows Communication

Prefacexxiv

Page 8: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Foundation (WCF)—that amazing, transport-agnostic, messaging-unification machine. When WCF finally came out, it supported WS-* andsome very basic REST/POX messaging. A few folks on the team were hardat work adding first-class REST support in the form of URI templates andextra functionality for HTTP-hosted services that were later released in.NET 3.5. Why this focus on REST? REST was starting to get very popular,thanks to Roy Fielding’s dissertation. Like many in the Web service com-munity, I read his dissertation many times, trying to really understandwhat made the Web scale as well as it did. When the WCF 3.5 bits startedcoming out as previews, I checked out the greatly improved REST sup-port. I was getting excited by what I was seeing and learning. In thebroader community and at work, I was finding that people were gettingmore and more comfortable using HTTP as a communication medium tocreate, retrieve, update, and delete resources.

I also started seeing the value in easy-to-type URLs. Furthermore, Ifound that the architecture and code just makes sense to developers.During 2006, I taught several multiday classes on WCF and gave presen-tations on WCF at a few conferences across the country. My talks on RESTwere well received. My talks on WCF internals weren’t. People appreci-ated the elegance of what WCF can do. They just did not see the value inthe steep learning curve one had to traverse to master the technology. Thething that pushed me over to REST was the realization of why people wereflocking to REST over WS-*. In general, developers used Web browsersand built Web applications long before they ever had to add a service ofany kind. REST development builds on what Web developers alreadyknow, so there is less to learn. WS-* might be elegant and cover many sce-narios, but it does not build on what most developers in most shops acrossthe globe already know.

In the summer of 2008, I joined the development team at MySpace asan architect. Guess what architectural style one of the world’s largest .NETsites uses to handle access to Friends, photo albums, and other resources.Yes, it’s REST. The platform is, first and foremost, a Web platform. RESTholds more value for HTTP base endpoints than a WS-* one ever will.REST integrates well with so many other platforms without a whole lot ofeffort. It doesn’t impose structure on the payload contents—only on the

Preface xxv

Page 9: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

payload metadata. REST is a model that novice developers understandand that expert-level developers can easily manipulate. I love the fact thatit is penetrating so much of service development. My day job involvesworking on OpenSocial—already one of the most successful REST APIsever developed. Through my work with OpenSocial, I have seen thatHTTP and REST compose well with many different security mechanisms.I find it interesting that WS-* protocols compose well with other XMLmechanisms. REST composes with other HTTP mechanisms. After spend-ing so many years working with SOAP and other RPC mechanisms, I likewhat REST has to offer.

How This Book Approaches REST

Today, we use this stuff. We build solutions based on this stuff. We like thisstuff. And we’re truly glad to have this book in our hands as architects anddevelopers. Both authors and the entire team behind this book hope youwill find it informative and useful as well.

One thing we didn’t want was a 1,000-page monster. When you under-stand REST, the concept is actually simple, and applying .NET technolo-gies to create RESTful solutions becomes a relatively easy task. If it can’tbe explained in a few pages, something’s not right.

The first couple of chapters introduce you to the concepts involvedwith REST. In a sense, you’re taken back to the earliest days of the Internetto rediscover how the Internet works and how the architectural conceptknown as REST fits into the Internet ecosystem so well. The first chapter,“RESTful Systems: Back to the Future,” addresses REST itself, and youlearn what it means to be RESTful and how to identify behaviors that arenot RESTful. Chapter 2, “The HyperText Transfer Protocol and theUniversal Resource Identifier,” is devoted to HTTP and the URI. These arethe two fundamental tools you’ll work with when developing .NET-basedsolutions.

Chapters 3 and 4 dig into the client side of the equation. RESTful serv-ices are there to serve a client’s needs, and there is no better way to beginto use REST than to consume RESTful services from a client’s perspective.There you learn what works and what doesn’t, with the lessons you learn

Prefacexxvi

Page 10: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

translating to design principles when you create RESTful services your-self. Chapter 3, “Desktop Client Operations,” shows you how to accessRESTful services from desktop applications (both authors believe that thedesktop is not a dead platform but is instead enhanced by Internet dataand service access), and Chapter 4, “Web Client Operations,” shows youhow to access RESTful services from Web-based applications, includingSilverlight 2.0. For consistency, both chapters access a single REST service.Later chapters build individual services unique to each chapter to increasethe breadth of exposure to different RESTful service implementations.

After you have a feel for how a client might use your service, it’s timeto dive into server-side programming. Here the book starts with the basics:what Internet Information Services (IIS) is, how it is put together, and howyou use it to implement RESTful services. Chapter 5, “IIS and ASP.NETInternals and Instrumentation,” leads you through the most foundationalserver-side technology: Microsoft’s premier Web server. Clearly this is onetechnology that supports nearly all the other .NET Web-based technolo-gies, RESTful or otherwise, and understanding how it works is crucial tobuilding effective REST services.

Chapters 6 though 8 then use higher-order .NET technologies to imple-ment RESTful services. Chapter 6, “Building REST Services Using IIS andASP.NET,” uses what you learned in Chapter 5 to create a Web blog serv-ice using only traditional ASP.NET constructs. Chapter 7, “Building RESTServices Using ASP.NET MVC Framework,” introduces you to theASP.NET MVC framework and shows how implementing a RESTful serv-ice might differ from traditional ASP.NET when you have the MVC frame-work to rely on. Of course, no .NET book discussing RESTful technologieswould be complete without digging into the nuts and bolts of WCF, andChapter 8, “Building REST Services Using WCF,” does just that.

The final chapter, Chapter 9, “Building REST Services Using Azureand.NET Services,” shows how you would combine cloud computingwith RESTful services to accomplish tasks that otherwise would be nearlyimpossible. In this case the sample application demonstrates a commentservice you can execute from behind your firewall on your private net-work. Your service will reach out and allow other people over the Internetwho are working behind their firewalls to work with your service.

Preface xxvii

Page 11: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

We then provide three appendixes we hope you’ll find helpful. Thefirst, Appendix A, “.NET REST Architectural Considerations andDecisions,” discusses some of the architectural aspects and why you mightchoose a particular .NET technology over another. Appendix B, “HTTPResponse Codes,” discusses each of the possible HTTP response codes andin particular what they mean to RESTful services and clients. And, finally,Appendix C, “REST Best Practices,” tries to provide some concise guid-ance for creating RESTful services.

Let’s face it. When it comes to writing effective software, the more youknow, the more effective your software will be. Although we don’t assumethat you’re the world’s foremost expert on writing ASP.NET applications,we do believe you’ll have some real-world .NET experience before read-ing this book. We’re going to be working at some of the lowest levels ofHTTP, IIS, and even ASP.NET, so some familiarity with each of these is aplus. But neither is this book a 1,000-page monster, so if there are bits andpieces you’re not so familiar with, there should be plenty here to introduceyou to concepts and techniques you’ll find useful in your daily work.

Finally, we’ve set up a Web page in addition to the publisher’s pagewhere you can send comments and questions directly to us. If anyone(gasp!) finds…inconsistencies…in our sample software, we’ll postupdated code there for you to download. Interesting and informative tid-bits might find their way there as well, time permitting. Both authors earntheir living writing software just as you do, and we’re every bit as busy asyou are making ends meet with the world economy the way it has been inthe latter part of 2008. But both authors love this architectural concept andare committed to helping you understand and use it as well. So if interest-ing and informative things come up, we’ll put them on the book’s Webpage:

www.endurasoft.com/rest.aspx

Prefacexxviii

Page 12: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

7Building REST Services UsingASP.NET MVC Framework

I N CH A P T E R 6 we created a basic RESTful service using bare-bonesASP.NET techniques such as implementing an HTTP handler that rep-

resents our service. Interestingly, this isn’t far from what happens with theASP.NET MVC framework, but we don’t look at it quite that way. More-over, we gain some niceties revolving around URL routing and controlleraction invocations.

The ASP.NET MVC Framework

In mid-2007 or so, Microsoft introduced a new way to build ASP.NET appli-cations that is based on the classic model-view-controller (MVC) designpattern. Although we could argue whether it fits the true MVC pattern orthe more contemporary front controller pattern, the idea is that the tradi-tional Web Forms method of creating Web pages is replaced by a frame-work that is actually based on RESTful principles. If you’ve not tried theASP.NET MVC framework, it is available for download from this URL:http://www.asp.net/mvc

245

Page 13: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Traditional Web pages are rooted in disk files, and the representationthey offer is the rendered HTML that comes from either the HTML storedin the file or, in the case of ASP.NET, the page offered up by the ASP.NET��!���':�/P�.�&/+. Consider what happens when you enter a URI suchas the following:

)�� ���<<<�.&'�&�&�.&���C������ ,

Here, ASP.NET receives the incoming request and shuttles it to the��!���':�/P�.�&/+. ��!���':�/P�.�&/+’s job is to locate the compiledcode that represents the requested page. This code, based on 1��� ��':�/,then passes through a series of what amounts to workflow steps to renderthe HTML that is ultimately returned to the client. In the end, though,whether the client requests an HTML page or an ASP.NET page, the URIthey use targets a resource that (typically) resides in a specific file on disk.And if you’re using ��!���':�/P�.�&/+, the representation the client willreceive is HTML or some dialect of HTML, like XHTML.

The ASP.NET Web Forms model uses two files most of the time. The firstfile is a markup file that contains basic HTML and ASP.NET-specificmarkup that indicates which controls the page handler will instantiate andotherwise manipulate. The second file is called the “code-behind” file (orsometimes “code-beside”), and it contains programming logic in yourchoice of .NET language. As far as it goes, this page mechanism is fine andit works. But there is a tight coupling that exists between the markup andthe logic that drives the page since the markup and code-behind pages areclosely related. This doesn’t separate the view from the logic behind theview, which causes difficulties when considering such things as automatedunit testing or test-driven design, or even when trying to inject standardpractices like separation of concerns. Although much can be done by devel-opers to mitigate this tight coupling, in practice most development teamsdon’t (or can’t) make the investment because it is not self-evident, and itrequires planning, training, and code review to ensure consistent imple-mentation. Ironically, these techniques involve separating the data, the userinterface, and the manipulation of that user interface—which in itself is aform of MVC.

Moreover, ASP.NET had received negative comments from time to timefrom some in the developer community due to the way the Web Forms

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework246

Page 14: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

page is rendered. These developers consider the Web Forms page render-ing process to be “heavy,” meaning it takes too long and requires too muchserver resource to render a simple page. Authoring and rendering ASP.NETcontrols isn’t a simple process either, and at times scalability can beimpacted. In addition, the Web Forms model is inherently stateful, usinginformation caches such as view state, control state, and even the easy-to-access session state. It’s entirely too easy to get yourself into troublewhen implementing a Web site with more complexity than simple contentpages.

The ASP.NET MVC Framework 247

NOTE

It isn’t my intention to argue the merits or demerits of either ASP.NETplatform here. In my opinion both Web Forms and ASP.NET MVC aregood and have beneficial uses. To me it’s more a matter of selecting theproper tool for the job. Web Forms are more resource-centric whereasASP.NET MVC is more action-centric. Web Forms give you some pro-gramming niceties, because view state isn’t necessarily a bad thing attimes, whereas ASP.NET MVC allows you to program “closer to themetal.”

I also found the MVC framework to be a wonderfully RESTful plat-form, but I understand Microsoft doesn’t necessarily agree with thissentiment, preferring for developers to instead use Windows Com-munication Foundation services. The ASP.NET MVC framework is aterrific platform on which to build RESTful solutions using the veryconstructs the framework itself provides, but I also understandMicrosoft’s position. In practice, I think you should decide for yourselfbased on your application’s requirements. I wouldn’t hesitate to createa RESTful solution based on ASP.NET MVC if that best fit my applica-tion’s needs.

The ASP.NET MVC framework was created to address these issues, andyou can download the framework as well as learn much more about it athttp://asp.net/mvc. The ASP.NET MVC framework is built using a mod-ified version of the venerable model-view-controller pattern, the originalconcept for which is shown in Figure 7.1. Although you won’t find this fig-ure in the original source material, the idea Figure 7.1 embodies comes from

Page 15: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

the original source, which you can find at http://heim.ifi.uio.no/~trygver/1979/mvc-1/1979-05-MVC.pdf. I used the word “modified” onlybecause when creating a new ASP.NET MVC project, you’re given sampleviews and controllers. However, any model creation is up to you, so imple-menting the feedback to the view is therefore also up to you to implementshould you choose to do so.

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework248

View

Controller

Model

User interactswith the view

Invoke actionon controller

Perform task,interact withModel

New View?Create newmodel-view-controller set

Notify view ofchanges

Figure 7.1: Original model-view-controller pattern

NOTE

If you’re wondering about the feedback line on the right side of thediagram (as I was for a long time), it comes from the definition of theview in the aforementioned reference. Other patterns, like the model-view-presenter (and more contemporary patterns based on MVC, likethe front controller pattern of which the ASP.NET MVC framework isbuilt around) often seek to address things such as this direct model-view feedback or provide for other pattern optimizations.

Page 16: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

The model-view-controller pattern was revolutionary in the sense that itclearly separated the user interface–specific rendering (the view) from thelogic that drives what is shown. User actions, such as button clicks, arepassed from the view to the controller, which will either create a newmodel-view-controller set (such as when redirecting to a different Webpage) or interact with the model, which is where both the application logicand the data access reside.

The ASP.NET MVC framework relies on the ;/�&��3'!$&:�� toshuttle Web server requests to the $5.��� ��':�/, which then interpretsthe requested URL and activates the appropriate controller. Controller acti-vation is therefore ultimately based on the URI, and a controller action(method) is activated instead of directly targeting a disk-based resource. Atits very core, the ASP.NET MVC framework is based on RESTful principles!

In fact, think back to the preceding chapter. Remember the virtualnature of the service I created? The A&!��/53.��didn’t actually exist as a��� , or ���), file but rather was created and registered through the useof ;/3�� �����F�. By adding items to the ;/3�� �����F� and thenlater checking the incoming URI against the preregistered URIs the servicewould accept, the service could discern valid URIs, at least from the serv-ice’s point of view. It could then also dispatch the processing of those URIsalong with matched information, such as the parsed F&!1�.

This is very similar to the mechanisms I just described when looking atthe ASP.NET MVC framework. The framework provides a moreprogrammer-friendly and standardized way to execute your own code (theA&!��/53.� is fully custom, after all), but the process for accessingresources is very, very similar in both cases. Let’s now look at some MVCframework details.

URL RoutingThe URL routing module is driven by “mapped routes,” which are URIsyou specify and couple to a specific controller. This process is much likesetting up the ;/3�� �����F� in the preceding chapter. Here is theroute map for the default route when you create a brand-new MVC Webapplication:

The ASP.NET MVC Framework 249

Page 17: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

/&�����$� �&���7?��C���?�?H.&'�/&�/J�H�.�3&'J�H3:J?�'�<�H�.&'�/&�/�0�?�&�?���.�3&'�0�?1':�,?��3:�0�??�J

8-

��C��� is the name of the route, and you can imagine that this is used asa key in a route table (undoubtedly a dictionary object). The value H.&'��/&�/J�H�.�3&'J�H3:J is the “designed” URI, which essentially says thismapped URL will be activated like so:http://servername/virtualdirectory/controller/action/idIf no controller is specified, it will default to �&�%&'�/&�/. The MVCframework will take the value placed in the route map, �&�, and auto-matically concatenate the word %&'�/&�/ to look up the appropriate con-troller class in the %&'�/&�/� folder, which in this case is �&�%&'�/&�/.If no action is specified, the MVC framework will examine the �&�%&'��/&�/ class for a method named 1':�,. However, if the URIhttp://servername/virtualdirectory/Home/Aboutis used, then the MVC framework will invoke the F&�� method containedwithin the �&�%&'�/&�/.

In both sample URLs there was no 3: value. None was specified in theURL, and the 1':�, and F&�� methods contained within the �&�%&'��/&�/ have no parameters to deal with it since none is expected for thoseactions. However, if you created a blog and provided an action that listedpages in your blog, the 3: value could become the page number:

�F3.� .�3&'��������!�71'�#��3:8H

���J

In this case, the URL for page 3 of your blog would be this:http://servername/virtualdirectory/Home/Page/3The �&�%&'�/&�/’s ��!� method would be invoked and passed thevalue # as the 3: parameter. You’d then process the page number usingwhatever logic makes sense for locating and displaying the desired view.

There is a special case this chapter’s service takes advantage of when itregisters the RESTful service URI with the URL routing framework, andthat is the parameter wildcard. If your application has the specific pattern

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework250

Page 18: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

the default route maps for you, which is controller, action, and then ID, thedefault route works fine. But if your application might have a URI thatvaries, you could map your route using the wildcard and decide what to dowhen your controller is invoked. Here’s an example:

/&�����$� �&���7?9�/3�F�;�1?�?H$+%&'�/&�/J�HN.&'��'�;/3J?�'�<�H�.&'�/&�/�0�?$+%&'�/&�/?���.�3&'�0�?��/53.��������?�J

8-

This URI is registered using the 9�/3�F�;�1 name, but it can be acti-vated using an infinite number of URIs, all of which map to $+%&'�/&�/’s��/53.�������� action method. The remainder of the URI is provided tothe ��/53.�������� method as a string parameter. You’d use this if yousimply can’t define the URI for all possible client invocations or your URIwill vary. Later in the chapter I’ll show you how to register a new route inthe route map.

Controller ActionsNote that the ��!� method shown previously returns something known asan .�3&'�����. You might imagine an .�3&'����� returning some ren-dered HTML value, but in fact an .�3&'����� is simply an abstract classdefined as such:

�F3.��F��/�.��.���� .�3&'�����H

/&��.��:� .�3&'�����78-

�F3.��F��/�.��5&3:��,�.��������7%&'�/&�/%&'��,��.&'��,�8-J

Several concrete .�3&'����� classes are shipped with the ASP.NET MVCframework, including 93�<�����, which is returned from the controller’s93�< method (I’ll discuss this in a bit more detail in a following section),��:3/�.��&�&��������, and ��/�3�93�<�����. Of course, nothing saysyou can’t create your own, and I did exactly that when creating the REST-ful service for this chapter. (And of the six cases the service handles, onlyone of those cases returns HTML to the client.)

The ASP.NET MVC Framework 251

Page 19: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

As I alluded to earlier in the chapter, URIs are mapped to controlleractions (not disk files as with traditional ASP.NET). Controller actions areimplemented by methods hosted by your controller classes that return .�3&'����� values. The behavior of the controller action in most caseswould be to spin up a ��� , page (the view), but though this is common,it isn’t required. Your controller can take other actions, depending on yourapplication’s needs.

Accepting HTTP MethodsA nice feature of the ASP.NET MVC framework is the capability to sepa-rate controller actions based on HTTP method. That is, you can specify onecontroller action for HTTP ��� and another for ����, �;�, ��(���, or what-ever. Coupled with this concept is the capability to overload the naming ofthe methods from the framework’s point of view. This is a great feature forRESTful services in which you generally support more than HTTP ���.

Let’s look at an example. Here is a valid URI for this chapter’s sampleservice, %&:���%:

)�� ������/5�/'���53/���:3/�.�&/+�%&:���%

You can imagine %&:���% as a simple-minded source code repository. If aclient accessed this URI, to determine what to do, you would need to exam-ine the HTTP method. If it was �� �, you would do one thing. If it was ���or ����, you would do another. To accomplish this, you would probablywrite code that used a switch statement using the HTTP Method to decidewhat to do:

�F3.� .�3&'������1':�,78H

�<3�.)�7�)3����� %&'��,������������� $��)&:��&(&<�/788H

.����?)��:?�����&�������� �/���/'��3� ��.)���:78-

.����?!��?�����&���������/���/'��3� ��.)���78-

.����? ��?�����&�������;�/���/'��3� ��.)���78-

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework252

Page 20: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

.����? &��?�����&����������/���/'��3� ��.)�&��78-

.����?:����?�����&�����������/���/'��3� ��.)�����78-

:�C�������;'K'&<'���)&:�� /&.�����//&/F/��K-

J

����/&.�����//&/�3� ��.)�//&/$��)&:6&� &<�:78-

J

In fact, this is precisely what you saw in the preceding chapter. It’s anotherexample of a dispatch table in which the appropriate service handler isinvoked based on HTTP method. It’s also very much “boilerplate” codethat could be rolled into a framework, and that’s exactly what was done inASP.NET MVC.

But then we have an issue. We can’t have identically named methodswith identical method signatures. If the framework can route actions to acontroller based on HTTP method, then there has to be some way to over-load the name of the method so that we don’t have syntactical errors. Thatis, we can’t have this situation:

���������� �> �F3.� .�3&'������1':�,78H

���J

�����������> �F3.� .�3&'������1':�,78H

���J�������������(���> �F3.� .�3&'������1':�,78H

���J

The ASP.NET MVC Framework 253

Page 21: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Clearly this won’t compile, but this is exactly the situation we wouldhave since a single URI serves all HTTP methods (keeping the original serv-ice URL in mind: https://servername/virtualdirectory/CodeXRC).

It’s for this reason the ASP.NET MVC framework coupled the ability tohandle different HTTP methods with different controller actions using analiased name. The ..� �9�/F� and .�3&'6�� attributes cleanly disam-biguate the HTTP method and aliased name:

���������� �Q ..� �9�/F�7?�� �?8RQ .�3&'6��7?1':�,?8R �F3.� .�3&'�������/&.������:78H

���J

�����������Q ..� �9�/F�7?���?8RQ .�3&'6��7?1':�,?8R �F3.� .�3&'�������/&.������78H

���J�������������(���Q ..� �9�/F�7?��(���?8RQ .�3&'6��7?1':�,?8R �F3.� .�3&'�������/&.��������78H

���J

In this case I’ve rewritten the previous example to show the proper tech-nique. From a URI perspective, the controller action is always 1':�,. Butthe true controller action to be invoked will depend on the HTTP methodused to invoke the action. If the HTTP ��� method is used, the �/&.������action is invoked, and so forth.

This chapter’s sample RESTful service makes heavy use of this new fea-ture, and I’d expect that many services will do so over time as well.

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework254

Page 22: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

ViewsAlthough this book isn’t about building Web sites using ASP.NET MVC, Ithought a paragraph or two that describes how the views are handled isappropriate since I’m introducing the framework.

The ASP.NET MVC Framework 255

NOTE

You’ll find that I didn’t make use of the view capability in the chapter’ssample application. Perhaps I should have. I certainly could have. Ijust found it more convenient to take the notion of a controller “action”literally and have the controller address the service request. The pointwas not to render a “view” but to respond to a call for action, even ifthat action results in rendered HTML. Had I been building Web pages,I would have done things differently. (If you disagree with my imple-mentation, that’s fine. When you build your own services, by all meansfollow your own interpretation of the pattern.)

The ASP.NET MVC framework uses a folder (conventionally) named93�<� to contain all the views, with views associated with a particular con-troller in a subfolder named after the controller. Views associated with the�&�%&'�/&�/, for example, are found in the �&� folder, which is a childfolder of 93�<� in the main application directory. If all you ever do is invokethe view associated with the action, the MVC framework will automaticallyselect the view named for the action. For example, the default �&�%&'��/&�/ has an F&�� action that invokes the F&�� view in the �&� folderof the 93�<� Web application directory. This code does that job, with theMVC framework’s help:

�F3.�.�����&�%&'�/&�/���%&'�/&�/H

��� �F3.� .�3&'������ F&��78H

93�<����Q?�3��?R�0�? F&�����!�?-

/���/'�93�<78-J

J

Page 23: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

The F&�� action returns a 93�<����� from the controller’s base 93�<method, which implements the algorithm I mentioned for locating thedefault view for the action. And as you recall, 93�<����� is derived from .�3&'�����.

However, you might want to use another view, and as it happens thecontroller’s base 93�< method is overloaded, allowing you to select otherviews based on name. One I find myself using a lot is this overloadedversion:

/&��.��:�3'��/'��93�<������93�<7��/3'!�53�<6����&FO�.��&:�8-

With this overloaded version, you provide the name of the view you wouldrather invoke as well as some page-specific data the view can accessthrough its 93�<���� property (specifically 93�<�����$&:�). Perhaps youhave one view that’s based on a data grid and another based on a chart.Using this overloaded 93�< method, you can select the most appropriateview based on your application’s needs.

You also can redirect to another page entirely. The simplest way is to usethe controller’s ��:3/�.� method, which returns a ��:3/�.� .�3&' object.But other redirect methods exist, such as ��:3/�.��& .�3&' and ��:3/�.��

�&�&���. Of course, these allow you to redirect to a different controlleraction or mapped route.

The ModelIn MVC terms, the model is where you place your data access layer and anyapplication-specific business logic. When you create a brand-new ASP.NETMVC Web application, the project wizard creates controllers and views foryou as starter code. But no model is created—only a subdirectory is createdfor you within which you place model code. Nearly all the %&:���% serv-ice functionality is implemented in classes that are housed in the modelfolder, and you’ll find this is typical for MVC-style applications.

ASP.NET MVC SecurityASP.NET MVC incorporates the notion of an ��)&/3L� attribute and the ..&�'�%&'�/&�/ class. Imagine a controller that looks somethinglike this:

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework256

Page 24: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

�F3.�.����$+%&'�/&�/���%&'�/&�/H

���Q ��)&/3L�R �F3.� .�3&'�������&�&��)3'!78H

���J

J

The ��)&/3L� attribute causes the ASP.NET MVC handler to look for acontroller named ..&�'�%&'�/&�/ and invokes its (&!3' action. The(&!3' action, and the ..&�'�%&'�/&�/ for that matter, are designed towork with the ASP.NET Forms Authentication module. Therefore, (&!3'and ��!3���/ generate an authentication cookie, (&!&�� destroys thecookie, and everything else the account controller does favors the Formsauthentication process in ASP.NET.

After seeing the additional work ASP.NET MVC offered, which was towrap access to the Forms authentication services (or at least a couple ofthem) behind a custom interface, I thought it would be useful to try to workthe HTTP Basic Authentication module from the preceding chapter into theMVC framework. But the simple truth is that given the module from thepreceding chapter, the entire concept behind the ..&�'�%&'�/&�/, or atleast the Forms authentication parts of it, aren’t needed.

With Forms authentication, navigating between secured pages is accom-plished using the ASP.NET security cookie. The Forms Authenticationmodule looks for the cookie, and if it’s present and valid when accessingsecured resources, the Forms Authentication module allows the securedpage to render. The ��)&/3L� attribute controls which actions are secured.

HTTP Basic Authentication, however, doesn’t use a cookie. In fact, thisis what makes it so appealing to RESTful services. The client needs to cachethe credentials and offer them to the Web server each time access to asecured resource is desired. Modern Web browsers all do this for you, andmost (if not all) of the sample desktop applications in this book will alsocache the credentials for you if you choose so that each service accessdoesn’t force reauthentication.

In the end, I simply copied the module from the preceding chapter intothis chapter’s sample application, changed the namespaces involved, and

The ASP.NET MVC Framework 257

Page 25: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

made the necessary adjustments to the <�F�.&'C3! file, and the HTTP BasicAuthentication worked tremendously well. Since I didn’t require the ..&�'�%&'�/&�/, I deleted it and the views associated with it, knowingthat the browser itself would query me for my credentials—I don’t need a“login” page for that. True, I also then dismissed the registration and pass-word change request pages, but there is some merit for brevity when pro-ducing chapter samples.

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework258

NOTE

I also can’t use the spectacular ��)&/3L� attribute, but I found I didn’tneed it with the custom authentication module. If I were producing atraditional MVC Web application, one based on views, I’d embracethese new ASP.NET MVC tools—the account controller and securityattribute—but for a truly RESTful service that requires HTTP BasicAuthentication, I discovered they’re just not the right tools for the job.

Building an MVC RESTful Service—���-/�

With this understanding of the basic ASP.NET MVC framework, it’s time toactually build a RESTful service that relies on the framework for basic oper-ations. This service, unlike the blog service in the preceding chapter, won’tcreate an ��� ��':�/ to service the RESTful requests but will instead bebased on controller actions that are activated by the specific service URImapped in the URL routing table.

To show a service that did more than produce “Hello, World!” I decidedto implement the basis of a source code vault, or perhaps a cloud-based filesystem. The idea behind this is that you select files on your local hard driveand store them in this secured service. This is an aggressive service for theschedule I had to work with, but though it was becoming more complex thefurther I got into development, I was more convinced it made for a greatchapter sample because it addresses many interesting RESTful concepts.These will be evident when I discuss the URI design.

Page 26: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

I named the service %&:���%, the “XRC” part having no particular mean-ing except it isn’t copyrighted as far as I could tell. (I don’t want to upset thepublisher’s legal staff.) The URIs for the service are designed like so:

• Add/update a project: �;� to �%&:���%

• Add/update a project (alternate): �;� to �%&:���%�H /&O�.�J

• Add/update a project folder: �;� to �%&:���%�H /&O�.�J�HC&:�/J

• Add/update a file: �;� to �%&:���%�H /&O�.�J�HC&:�/J�H�,�J�

HC3�J

• Delete all projects: ��(��� to �%&:���%

• Delete a project: ��(��� to �%&:���%�H /&O�.�J

• Delete a folder: ��(��� to �%&:���%�H /&O�.�J�HC&:�/J

• Delete files by extension: ��(��� to �%&:���%�H /&O�.�J�HC&:�/J�

H�,�J

• Delete a file: ��(��� to �%&:���%�H /&O�.�J�HC&:�/J�H�,�J�

HC3�J

• Get all projects (high level): ��� to �%&:���%

• Get a project (all folders/files): ��� to �%&:���%�H /&O�.�J

• Get a folder: ��� to �%&:���%�H /&O�.�J�HC&:�/J

• Get files by extension: ��� to �%&:���%�H /&O�.�J�HC&:�/J�H�,�J

• Get a file: ��� to �%&:���%�H /&O�.�J�HC&:�/J�H�,�J�HC3�J

• Get statistics/headers: �� � to a valid service URI

Building an MVC RESTful Ser vice—���-/� 259

NOTE

Although not provided with this chapter’s sample application, theASP.NET MVC framework is perfectly suited for creating test-drivendesign (TDD) applications. Creating applications using test-driventechniques tends to reduce the number of latent bugs and increasescode maintainability.

Page 27: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

This complex-looking set of URIs really amounts to simulating a file sys-tem using REST (see Figure 7.2).

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework260

Folder

Folder

Folder

FolderProject

File

File

File

File

Folder

Figure 7.2: %&:���% project storage

The files are stored on the server’s file system in the hierarchy shown inFigure 7.2, but there is also a database associated with the service to main-tain ownership of the projects and files as well as foreign key relationshipsfor searching and deletion. Users are registered using a process not pro-vided with the service, but when they’re registered their account informa-tion is stored in the typical ASP.NET tables contained within the database.Projects are owned by the registered users and are identified by their userID, which is a ��3:. Roles are also maintained: View, Insert, and Delete. Atpresent the service allows you to access only your own projects, but itwould be a relatively easy extension to add View capabilities to projects notyour own.

Creating the URL MappingWith the URI set defined for the service, the place to start is with the URLrouting table and mapping. To do this, you open the �&F�����,�.� fileand look for the ��!3���/�&���� method. There, you’ll see the default routemapped into the route table (this is created for you by the Visual StudioMVC application wizard). Add this code just before the default route:

Page 28: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

�����!3���/��)������C����/53.��;�1����'&����)3��N$;��N���.&��F�C&/���)��:�C����;�1�� 3'!�&/�+&�Z������3'���I�I��//&/��3C��)��;�1�:&��'Y����.)��)��:�C������� 3'!�/&�����$� �&���7

?%&:���%?�?%&:���%�HN.&'��'�;/3J?�'�<�H�.&'�/&�/�0�?%&:���%?���.�3&'�0�?��/53.��������?�J

8-

Of course, this looks a lot like the mapping I discussed previously in thechapter, and given the variable nature of the URI set, you can probably seewhy I opted for the wildcard approach.

Building an MVC RESTful Ser vice—���-/� 261

NOTE

You could individually map each URL segment and apply a default, asis done with the Default URL route map, but I chose to simplify theaction signatures and parse the URI manually.

When requests come into the server designated for the %&:���% service,the %&:���%%&'�/&�/ will be called on to take the appropriate action. Asis proper for the ASP.NET MVC framework, the %&:���%%&'�/&�/ islocated in the Web application %&'�/&�/� folder.

The ���-/��� ""� The %&:���%%&'�/&�/ contains four actions, one for each HTTP methodthe service handles: HTTP �� �, ���, �;�, and ��(���. Each action isadorned with the appropriate ..� �9�/F� and .�3&'6�� attributes. The�� � action is shown in Listing 7.1.

Listing 7.1: The %&:���%%&'�/&�/ HTTP �� � action

Q ..� �9�/F�7?�� �?8RQ .�3&'6��7?��/53.��������?8R �F3.� .�3&'���������:�������7��/3'!�.&'��'�;/38H

���P3��/��)�����/+���/3'!��':�/�&5���'+��/�33'!�Y�Y��&���<��:&'Y��)�5���'��,�/���//�+����'��.&'��'�;/3�0�P3��/;/37.&'��'�;/38-

continues

Page 29: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Listing 7.1: Continued

�����5���)��;�1� �/����/���/3'!QR�:3/�.�35���0�'�-3C�7S��/3'!�1�6��/� �+7.&'��'�;/388H

:3/�.�35���0�.&'��'�;/3�� 3�7Y�Y8-J

������ ����&����� &/�/+���/��$�&/+��/�����/�0�'�<�$�&/+��/��78-�)3����� %&'��,��1���� ::7?��� ����/��?����/8-

�����':���)��/������%&:���%�����/53.��/�����0�'�<�%&:���%�����/53.�7:3/�.�35�����/��8-/���/'�/����-

J

In Listing 7.1 you can see that the controller action is named ���:��������, but because I applied the .�3&'6�� attribute, the ASP.NET MVCframework will route the action as if it were named ��/53.��������, whichmatches the name of the action I registered in �&F�����,�.�. And sincethe ..� �9�/F� attribute lists only HTTP �� � as the accepted HTTPmethod, this action is called only for �� � requests.

The parameter .&'��'�;/3 will contain anything on the query stringpast the controller name. That is, if the client issued a request to the URIhttp://servername/AspNetMvcRestService/CodeXRC/Project1/Folder2/cs/CodeFile3the .&'��'�;/3 parameter would contain the string �/&O�.���P&:�/��.��%&:�P3�#.

To decide what parameters are present, the .&'��'�;/3 string is splitusing the slash as the delimiter. However, I filter the string first to removea trailing slash. This prevents a phantom entry in the resulting string array.That is, this URI would result in three parameters after the string split:http://servername/AspNetMvcRestService/CodeXRC/Project1/Folder2/In reality, though, only two parameters are present: �/&O�.�� and P&:�/�.The third entry in the string array would be an empty string, present onlybecause of the trailing slash. By removing the slash, the service doesn’tneed to check for empty parameter elements in the parameters string array.

In the case of HTTP �� �, the service will perform all the normal ���processing. However, the stream the information is written to will differ for

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework262

Page 30: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

the other HTTP methods. For example, ��� will use the actual outputstream, thus sending a response to the client. �� � will use a temporarystream, allowing the service to determine the size of the stream so that theappropriate %&'��'��(�'!�) header can be returned to the client. The out-put stream to use is assigned a slot in the ��� %&'��'� 1��� collection sothat it won’t need to be passed around as a separate method parameter inall the internal processing methods.

The request is handled by a class that derives from .�3&'�������:%&:���%�����/53.�. As you might imagine, there are corresponding serv-ice classes for �;� and ��(��� as well. Since ��� and �� � are closely related,a single service class handles both HTTP methods. Something to keep inmind is that the response output stream is not seekable, meaning we can’tquery its length. It would have been nice to simply write to the appropri-ate stream and just query the stream length, but unfortunately the responseoutput stream throws an exception when you access its (�'!�) property.This means you have to ask the question “Is this a �� � request?” If so, then(and only then) should you access the stream’s (�'!�) property and createthe %&'��'��(�'!�) header. I use the stream’s %�'���K property for that.

In contrast, the HTTP �;� method service controller action is shown inListing 7.2.

Listing 7.2: The %&:���%%&'�/&�/ HTTP �;� action

Q ..� �9�/F�7?�;�?8RQ .�3&'6��7?��/53.��������?8R �F3.� .�3&'����������������7��/3'!�.&'��'�;/38H

���P3��/��)�����/+���/3'!��':�/�&5���'+��/�33'!�Y�Y��&���<��:&'Y��)�5���'��,�/���//�+����'��.&'��'�;/3�0�P3��/;/37.&'��'�;/38-

�����5���)��;�1� �/����/���/3'!QR�:3/�.�35���0�'�-3C�7S��/3'!�1�6��/� �+7.&'��'�;/388H

:3/�.�35���0�.&'��'�;/3�� 3�7Y�Y8-J

������ ����&��)���/���/�� &'�����/���)3����� %&'��,��1���� ::7?��� ����/��?�

�)3����� %&'��,����� &'������ ����/��8-

Building an MVC RESTful Ser vice—���-/� 263

continues

Page 31: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Listing 7.2: Continued

�����':���)��/������%&:���%�����/53.��/�����0�'�<�%&:���%�����/53.�7:3/�.�35��8-/���/'�/����-

J

I’ve included the ���������� method here only to highlight the differ-ences: the HTTP method it accepts is �;�, the controller action is actually��/53.�������� even though the controller method is called ����������,the stream to be used for the response is the true output stream (versus atemporary one), and the �;� behavior is exhibited by the %&:���%�����/53.� class. Otherwise, the request handling for each HTTP method issimilar at the controller level.

���-/��Service ClassesAll the %&:���% service classes use .�3&'����� as their base class. In fact,there is a single %&:���% service base class, %&:���%��/53.�A���, that isused to maintain instances of the URI parameters (which I called “direc-tives” because they direct the service), the data access component, and anauxiliary component that sports helper methods for supporting errorresponses and such. This base class is shown in Listing 7.3.

Listing 7.3: The %&:���%��/53.�A��� class

�F3.�.����%&:���%��/53.�A������ .�3&'�����H

/&��.��:�%&:���% �,��/53.���G��,�0�'�<�%&:���% �,��/53.��78- /&��.��:�%&:���%���� ..����G:��0�'�<�%&:���%���� ..���78- /&��.��:���/3'!QR�G:3/�.�35���0�'�<���/3'!Q�R-

�F3.�%&:���%��/53.�A���78HJ

�F3.�%&:���%��/53.�A���7��/3'!QR�:3/�.�35��8H

���(���/�&!3.�:� �':��&'��)3��'&��F�3'!���'���5�'�3C�3��)���'&����'���3C�7:3/�.�35���S0�'�8H

��� ��3!'�5���G:3/�.�35���0�:3/�.�35��-

J

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework264

Page 32: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

J

�F3.��F��/�.��5&3:��,�.��������7%&'�/&�/%&'��,��.&'��,�8-H

����3��&<�F����3 ��'���3&'���'&���+&��.�'Y���K�����)3���F��/�.���3'.���)3��.����3��3���C�:�/35�:��':����)3����)&:�&5�//3::�'��)/&<�'�<�6&�1 ��'��:�,.� �3&'7?\&������&5�//3:���)��F�����,�.���������3 ��'���3&'�?8-

JJ

Since all the derived classes need to use the data access component, theauxiliary helper method component, and the directives, it made sense tocollect that in a base class.

Returning HTML, XML, and JSON

The services themselves are broken out into “get,” “put,” and “delete” ver-sions, each handling the respective HTTP method. Each service methodhandler also overrides the .�3&'����� �,�.�������� method. The%&:���%�����/53.� implementation is shown in Listing 7.4. The otherimplementations are similar.

Listing 7.4: %&:���%�����/53.���,�.�������� method

�F3.�&5�//3:��5&3:��,�.��������7%&'�/&�/%&'��,��.&'��,�8H

���������)�����/Y��./�:�'�3��3C�7.&'��,����� %&'��,��;��/�1�1'�&�7?93�<?88H

�/+H

3C�7.&'��,����� %&'��,���������� ..� ��+ ���%&�'�78�@��8H

���(&& ��)/&�!)��)��.&�.�3&'�&C��..� ��:��+ �������)��C3/���&'��<��)3��<���':�/���':����K��3����C&/��.)�7��/3'!��+ ��3'

.&'��,����� %&'��,���������� ..� ��+ ��8H

�<3�.)�7�+ ���&(&<�/788H

.����?��,��)�?�

.����?N�N?���':�/��7.&'��,�8-/���/'-

Building an MVC RESTful Ser vice—���-/� 265

continues

Page 33: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Listing 7.4: Continued

.����?��,��,?���':�/�7.&'��,�8-/���/'-

.����?� 3.��3&'�O�&'?���':�/V�&'7.&'��,�8-/���/'-

:�C��������/+�'�,��&'����F/��K-

JJ

���%&�:'Y���..� ���'+�/�������:��+ �G��,���':�/�//&/6&� ..� ��F����7.&'��,�8-

J���H

���%&�:'Y���..� ���'+�/�������:��+ �G��,���':�/�//&/6&� ..� ��F����7.&'��,�8-

JJ.��.)�7�,.� �3&'��,8H

���%&�:'Y���..� ���'+�/�������:��+ �G��,���':�/�//&/1'��/'��//&/7.&'��,����,��&��/3'!788-

JJ���H

���;��/�C&/F3::�'G��,���':�/�//&/P&/F3::�'7.&'��,�8-

JJ

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework266

NOTE

I am a fervent believer in application tracing, and for any Web appli-cation I write, I put as much tracing into the code as possible. However,for demonstration purposes here, I’ve omitted such code to focusinstead on the functional nature of the service itself. Tracing is criticalto debugging deployed Web applications and I heartily recommendusing it.

Page 34: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

In Listing 7.4 you can see that the code begins by checking the client’srole (the client was authenticated or this method wouldn’t be executing).If the client has the appropriate role credentials, the method then checks thedesired return type: HTML, XML, or JSON. The default content type, N�N,will return HTML. This allows browsers to view the contents of a project, asshown in Figure 7.3. The chapter’s sample client will always provide theservice with an ..� � header containing just one accepted content type,but because browsers often include many requested content types, the loopallows the service to check the list of content types for the first one the serv-ice has the capability of supporting.

Building an MVC RESTful Ser vice—���-/� 267

Figure 7.3: Browser REST service access

If you use the chapter’s Windows Forms sample client, you can interactwith the service in a greater variety of ways, including asking for the proj-ect contents as XML, as shown in Figure 7.4.

After the desired return content type is determined, the code in Listing7.4 then invokes the appropriate rendering method. Listing 7.5 shows youhow XML is rendered. I won’t show all the supporting methods becausethere are many, and they often are recursive (and therefore complex) sincethe methods often need to traverse directory structures. They’re also notimportant to demonstrate how to create RESTful services using the

Page 35: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

ASP.NET MVC framework, so I’ll leave spelunking their inner workings toyou. They’re just business logic, so to speak, and as such you’ll find themall in the $&:�� folder of the � 6��$5.������/53.� Web application.

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework268

Figure 7.4: CodeXRC project contents as XML

Listing 7.5: The ��':�/�$( method

/35����5&3:���':�/�7%&'�/&�/%&'��,��.&'��,�8H

�������)�����/Y��1����)3��<&/K��)�/���3'.��<�Y/����3'!��)������X(�F���:��F�/�)3 � /&53:�/�$�F�/�)3 ;��/����/�0$�F�/�)3 ����;��/7.&'��,����� %&'��,��;��/�1:�'�3�+�6��8-

��3:�&<'�/1��0�7��3:8���/��/&53:�/;��/��+-

.&'��,����� %&'��,����� &'���%&'��'��+ ��0�?��,��,?-�<3�.)�7G:3/�.�35���%&�'�788H

.������:�C����

���(3����� /&O�.���C&/����/����)�� ���H)&��J�H5:3/J�%&:���%��':�/��/&O�.�(3��7.&'��,���&<'�/1�8-F/��K-

.���������(3���� �.3C3.� /&O�.��C&/����/����)�� ���H)&��J�H5:3/J�%&:���%�H /&O�.�J��':�/��/&O�.�7.&'��,���&<'�/1���G:3/�.�35��Q�R8-F/��K-

Page 36: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

.���������(3���� �.3C3.�C&:�/�C&/����/����)�� ���H)&��J�H5:3/J�%&:���%�H /&O�.�J�HC&:�/J��':�/�P&:�/7.&'��,���&<'�/1���G:3/�.�35��Q�R�G:3/�.�35��Q�R8-

F/��K-

.����#����(3���C3���F+��,��'�3&'�C&/����/����)�� ���H)&��J�H5:3/J�%&:���%�H /&O�.�J�HC&:�/J�H�,�J��':�/�P3��A+�+ �7.&'��,���&<'�/1���G:3/�.�35��Q�R�G:3/�.�35��Q�R��G:3/�.�35��Q�R8-

F/��K-

.����I��������/'�� �.3C3.�C3���&����/����)�� ���H)&��J�H5:3/J�%&:���%�H /&OJ�HC&:�/J�H�,�J�HC3�J��':�/�P3�A+6��7.&'��,���&<'�/1���G:3/�.�35��Q�R�G:3/�.�35��Q�R��G:3/�.�35��Q�R��G:3/�.�35��Q#R8-

F/��K-J

��� ��3!'��)��.&'��'���'!�)��F���&'+�3C��� ����/�����/���0�.&'��,����� %&'��,��1���Q?��� ����/��?R������/��-3C�7��/���S0�'��EE���/���%�'���K8H

.&'��,����� %&'��,����� &'������:�/�Q?%&'��'��(�'!�)?R�0���%&'��'�(�'!�)7.&'��,�8��&��/3'!78-

JJ

The methods to render HTML and JSON are similar. Actually, renderingXML and JSON is easy using the ����%&'�/�.���/3�3L�/ and ����%&'�

�/�.�V�&'��/3�3L�/ objects, respectively. But the HTML is rendered byhand (again, one could perhaps use a view for this or augment the XMLoutput with an XSLT reference, but I chose to keep the service logically con-tained, for right or wrong). After the content is rendered, the stream isexamined for its length if the HTTP method was �� �.

An important aspect of returning a resource representation is creatingthe links (remember hypermedia as the engine of application state). Whenrepresentations are created, a special class is used to generate the appro-priate links, which are shown in Listing 7.6.

Building an MVC RESTful Ser vice—���-/� 269

Page 37: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Listing 7.6: The %&:���% link builder class

�F3.�����3.�.����%&:���%(3'KA�3:�/H

�F3.�����3.���/3'!�A�3:�/&O�.�(3'K7%&'�/&�/%&'��,��.&'��,����/3'!� /&O�.�6��8

H�����'�/�����)��3'K�7/��F�/�� ��� �8��/3'!�C�;/�0�.&'��,����� %&'��,����������;/��&��/3'!78-��/3'!�F���;/�0�C�;/���F��/3'!7���C�;/�1':�,�C7.&'��,����� %&'��,���������� 3.��3&'���)88-

/���/'���/3'!�P&/��7?H�JH�J�%&:���%�H�J?��F���;/�.&'��,����� %&'��,���������� 3.��3&'���)�� /&O�.�6��8-

J

�F3.�����3.���/3'!�A�3:P&:�/(3'K7%&'�/&�/%&'��,��.&'��,����/3'!� /&O�.�6�����/3'!�C&:�/6��8

H�����'�/�����)��3'K�7/��F�/�� ��� �8��/3'!�C�;/�0�.&'��,����� %&'��,����������;/��&��/3'!78-��/3'!�F���;/�0�C�;/���F��/3'!7���C�;/�1':�,�C7.&'��,����� %&'��,���������� 3.��3&'���)88-

/���/'���/3'!�P&/��7?H�JH�J�%&:���%�H�J�H#J?��F���;/�.&'��,����� %&'��,���������� 3.��3&'���)� /&O�.�6����C&:�/6��8-

J

�F3.�����3.���/3'!�A�3:P3�(3'K7%&'�/&�/%&'��,��.&'��,����/3'!� /&O�.�6�����/3'!�C&:�/6�����/3'!�C3��,��'�3&'���/3'!�C3�6��8

H�����'�/�����)��3'K�7/��F�/�� ��� �8��/3'!�C�;/�0�.&'��,����� %&'��,����������;/��&��/3'!78-��/3'!�F���;/�0�C�;/���F��/3'!7���C�;/�1':�,�C7

.&'��,����� %&'��,���������� 3.��3&'���)88-/���/'���/3'!�P&/��7?H�JH�J�%&:���%�H�J�H#J�HIJ�H2J?��F���;/�.&'��,����� %&'��,���������� 3.��3&'���)�� /&O�.�6���C&:�/6����C3��,��'�3&'��C3�6��8-

JJ

The link builder class simply encapsulates the logic in a single placethat’s necessary to build valid URIs for the various resources.

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework270

Page 38: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Creating Resources with XML

The only representation the %&:���% service accepts for creating newresources is XML, and the %&:���%�����/53.� �,�.��������method codeis shown in Listing 7.7.

Listing 7.7: %&:���%�����/53.� �,�.�������� method

�F3.�&5�//3:��5&3:��,�.��������7%&'�/&�/%&'��,��.&'��,�8H

���������)�����/Y��./�:�'�3��3C�7.&'��,����� %&'��,��;��/�1�1'�&�7?1'��/�?88H

���D�Y��..� ��&'+��$(�C&/�./���3'!�� :��3'!�����/��&�/.���D��.&�:��..� ��V��6����3+��F����)3����3��)&<�+&�Y:�33��3' �����&���� �.3C3.��+ ��3C�7.&'��,����� %&'��,����������%&'��'��+ ���&(&<�/78�00

?��,��,?8H

���%/������)��3':3.���:�/��&�/.�%/�������&�/.�7.&'��,�8-

J���H

���D��'Y���$(���G��,���':�/�//&/6&� ..� ��F����7.&'��,�8-

JJ���H

���;��/�C&/F3::�'G��,���':�/�//&/P&/F3::�'7.&'��,�8-

JJ

The �,�.�������� in this case checks for the appropriate role as well asXML as the content type, but only to return an error if the indicated typeisn’t appropriate. Therefore, there is only one “create resource” method,which is shown in Listing 7.8.

Listing 7.8: %&:���%�����/53.� %/�������&�/.� method

/35����5&3:�%/�������&�/.�7%&'�/&�/%&'��,��.&'��,�8H

�������)�����/Y��1����)3��<&/K��)�/���3'.��<�Y/����3'!�����)���X(�F���:��F�/�)3 � /&53:�/�$�F�/�)3 ;��/����/�0

Building an MVC RESTful Ser vice—���-/� 271

continues

Page 39: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Listing 7.8: Continued

$�F�/�)3 ����;��/7.&'��,����� %&'��,��;��/�1:�'�3�+�6��8-��3:�&<'�/1��0�7��3:8���/��/&53:�/;��/��+-

.&'��,����� %&'��,����� &'���%&'��'��+ ��0�?��,��)�?-�<3�.)�7G:3/�.�35���%&�'�788H

.������:�C����

���%/������� /&O�.��C&/����/�7<3�F����� �.3C3.� /&O�.�8����)�� ���H)&��J�H5:3/J�%&:���%%/�����/&O�.�7.&'��,���&<'�/1�8-F/��K-

.���������%/������ �.3C3.� /&O�.��C&/����/�7��.)3:�C&:�/�����':�C3��8����)�� ���H)&��J�H5:3/J�%&:���%�H /&O�.�J%/�����/&O�.�7.&'��,���&<'�/1���G:3/�.�35��Q�R8-F/��K-

.���������������� �.3C3.�C&:�/�7��.)3:�C&:�/���':�C3��8����)�� ���H)&��J�H5:3/J�%&:���%�H /&O�.�J�HC&:�/J%/����P&:�/7.&'��,���&<'�/1���G:3/�.�35��Q�R�G:3/�.�35��Q�R8-

F/��K-

.����#����������C3���F+��,��'�3&'�3'�� �.3C3�:�C&:�/����)�� ���H)&��J�H5:3/J�%&:���%�H /&O�.�J�HC&:�/J�H�,�J%/����P3�A+�+ �7.&'��,���&<'�/1���G:3/�.�35��Q�R�G:3/�.�35��Q�R��G:3/�.�35��Q�R8-

F/��K-

.����I����������� �.3C3.�C3�����)�� ���H)&��J�H5:3/J�%&:���%�H /&OJ�HC&:�/J�H�,�J�HC3�J%/����P3�7.&'��,���&<'�/1���G:3/�.�35��Q�R��G:3/�.�35��Q�R�G:3/�.�35��Q#R�M�?�?�M�G:3/�.�35��Q�R8-

F/��K-J

J

The code in Listing 7.8 is somewhat similar to the code for retrieving aresource representation in Listing 7.5. The URI is examined and the appro-priate resource is created. Of course, there is no need to return a content

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework272

Page 40: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

length, so that code is missing from Listing 7.8. The code to handle HTTP��(��� is similar to the code shown in Listing 7.8, so I won’t show that hereeither.

Returning Error Information

In the preceding chapter, error information was returned according to theapplication’s error handling configuration. For this service, I chose to returnexplicit error information as HTML I create at the point where the exceptionis caught. The %&:���% �,��/53.�� class provides several error responsemethods, with an example being the HTTP I�#� 7P&/F3::�'8 responseshown in Listing 7.9.

Listing 7.9: The %&:���% �,��/53.�� ��':�/�//&/P&/F3::�' method

�F3.�5&3:���':�/�//&/P&/F3::�'7%&'�/&�/%&'��,��.&'��,�8H

.&'��,����� %&'��,����� &'���������%&:��071'�#�8��� ������%&:��P&/F3::�'-

.&'��,����� %&'��,����� &'���%&'��'��+ ��0�?��,��)�?-��3'!�7��/��D/3��/�<�/�0'�<���/��D/3��/77��/��8.&'��,����� %&'��,��1���Q?��� ����/��?R88H

��/3'!A�3:�/��F�0�'�<���/3'!A�3:�/78-�F� �':7?=)�@=)��:@=�3��@%&:���%=��3��@=�)��:@=F&:+@?8-�F� �':7?\&���/��'&�����)&/3L�:��&��..�����)��/��&�/.��+&��?8-�F� �':7?/�������:�=F/�@=�F&:+@=)�@?8-<�/�D/3��(3'�7�F��&��/3'!788-<�/�P��)78-<�/�%&��78-

JJ

Other errors are handled in a similar manner.

The ���-/� Data Access Layer

The service’s data access is provided by the %&:���%���� ..��� class. I per-sonally generally prefer to provide data access service through an interfaceand use a strategy pattern to load the appropriate data access component,but here I keep the example simple and just deal with data access directly.

Listing 7.10 contains the data access code used to read the database andreturn all the user’s projects.

Building an MVC RESTful Ser vice—���-/� 273

Page 41: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Listing 7.10: The %&:���%���� ..��� (3���/&O�.�� method

�F3.�(3��=�/&O�.����@(3���/&O�.��7%&'�/&�/%&'��,��.&'��,�����3:�&<'�/1�8

H������/3�5���� /&O�.��%&:���%����%���������%&'��,��:���%&'��,��0'�<�%&:���%����%���������%&'��,�78-

5�/� /&O�.�X��/+�0�C/&� �3'�:���%&'��,���/&O�.��&/:�/F+� ��/&O�.�1�<)�/�� ��<'�/1��00�&<'�/1����.�� -

(3��=�/&O�.����@� /&O�.���0�'�<�(3��=�/&O�.����@78-C&/��.)�75�/� /&O�.��3'� /&O�.�X��/+8H

���%/������)��'�<� /&O�.��3���/&O�.����� /&O�.�1���0�'�<��/&O�.����7 /&O�.�8- /&O�.�1���(3'K�0�%&:���%(3'KA�3:�/�A�3:�/&O�.�(3'K7.&'��,��� /&O�.���3� �+6��8-

/&O�.��� ::7 /&O�.�1��8-J/���/'� /&O�.��-

J

As you can see from Listing 7.10, I make heavy use of LINQ to SQL, andyou’ll find this throughout the data access code. The LINQ to SQL contextis shown in Figure 7.5.

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework274

Figure 7.5: The %&:���% LINQ data context

Page 42: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

The foreign keys shown in Figure 7.5 make it easier to query for specificentities. The data access code also creates the folders and files, and when itdoes, it stores the local directory or file paths in the LocalStorage column forlater recall. The service stores all folders and files within the G���� sub-directory, but you could easily change this if you prefer. I selected it sim-ply because the service didn’t require any changes to file systempermissions to read, write, and delete files in that location.

The data is conveyed to the client using data transfer objects (DTO). I’veshown the �/&O�.���� in Listing 7.11, but the other DTOs are similar.

Listing 7.11: The project data transfer object

Q����%&'�/�.�76��� �.��0�?)�� ���<<<��':�/��&C��.&������6���?�➥ 6��0?�/&O�.�?8R �F3.�.�����/&O�.����H

�F3.��/&O�.����78HJ

�F3.��/&O�.����7�/&O�.��:F�/&O�.�8���)3�78

H���%& +� /& �/�3���)3���/&O�.�1��0�:F�/&O�.���/&O�.�1�-�)3���3� �+6���0�:F�/&O�.���3� �+6��-

J

�F3.��/&O�.����7�/&O�.��:F�/&O�.���P&:�/���QR�C&:�/�8���)3�7:F�/&O�.�8

H���%& +�C&:�/��)3��P&:�/��0�C&:�/�-

J

Q����$�F�/R �F3.�1'�#���/&O�.�1��H�!��-����-�J

Q����$�F�/R �F3.���/3'!��3� �+6���H�!��-����-�J

Q����$�F�/71�����3/�:�0�C���8R �F3.���/3'!�(3'K�H�!��-����-�J

Q����$�F�/71�����3/�:�0�C���8R �F3.�P&:�/���QR�P&:�/��H�!��-����-�J

J

Building an MVC RESTful Ser vice—���-/� 275

Page 43: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Each DTO provides several constructors, including a copy constructorthat accepts the corresponding LINQ entity. (Note that another way toapproach this is to create extension methods and keep the DTOs in a sepa-rate assembly, which has advantages from a code-separation standpoint,and the DTOs wouldn’t have to reference LINQ.) The client has similarDTOs I created using the same technique described in the precedingchapter—I queried the service for the appropriate XML and used ,�:��,�to create a corresponding C# class. I then removed the ���/3�3L�/attributes and replaced them with ����%&'�/�.���/3�3L�/ attributes.This is cheating a little since I had unfair knowledge as to how the XML wasgenerated, but you could use either serializer as long as you faithfullyre-create the XML the service requires.

The ���-/� Service ClientEven though this service will return HTML, to demonstrate creation anddeletion of projects, folders, and files, I created a Windows Forms client youcan use to experiment with the various aspects of the service. The clientwon’t exercise all aspects of the service. It only adds projects, whereas theservice will accept folders and files as well (but keep in mind you’ll needto provide correct foreign keys, which is typical of many RESTful serviceswhen updating resources).

The basic user interface you’ve already seen in Figure 7.4. The client alsouses a similar authentication dialog box as the preceding chapter’s client,so I won’t repeat that as well. However, adding a new project does meritsome description. The dialog box for this is shown in Figure 7.6.

The Create Project dialog box appears only when XML is selected as thecontent type, �;� is selected as the HTTP method, and you click the Executebutton. Other content types for �;� display an error dialog box; and otherHTTP methods don’t involve resource creation, so no error is necessary.

After you provide a project name, you can select folders or files. If youchoose to add folders, you’ll be presented with the dialog box shown inFigure 7.7.

After you select a folder, the child folders and files will be added to thetree view control shown in the Create Project dialog box. From this tree con-trol you can remove files and folders simply by selecting them and pressingthe Delete key.

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework276

Page 44: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Figure 7.6: The %&:���% .3�'� Create Project dialog box

Building an MVC RESTful Ser vice—���-/� 277

Figure 7.7: The %&:���% .3�'� folder browser dialog box

If you instead decide to add files directly to the project, the client cre-ates a virtual folder, with the same name as the project, and adds the filesto that. The service doesn’t add files directly to a project, but this is simplyan implementation detail you could change fairly easily if you wanted. Ikept this as a business rule simply to have the rule in play. My reasoningwas that projects and folders aren’t the same in the service I implementedeven though a project is implemented as a folder on disk. Figure 7.8 showsthe Create Project dialog box when files are added to the project directly.

Page 45: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Figure 7.8: Adding files directly to a project

In all cases the files are read as binary files and converted into Base64strings for transmission over the network. Base64, on average, introducesa 30% (or so) increase in size, but it’s the only safe way to send binary infor-mation over a network using XML. The client will convert the files intoBase64 and the service will convert them back into their original binaryform for storage; but the client is limited in the sense that it cannot recall thefiles. I’ll leave the implementation of that to you to complete, but the basicconversion logic is already present in the service itself. The service willreturn to the client the XML representation of a created project, but this is soyou could cache the foreign keys if you chose to do so. The contents of thefiles are wiped from the representation to conserve bandwidth.

Where Are We?

This chapter introduced the ASP.NET MVC framework and how you couldcreate classes based on .�3&'����� to handle RESTful actions andresponses. The ASP.NET MVC framework is based on the model-view-controller design pattern, or more accurately on the contemporary frontcontroller pattern. The actions you create are directly mapped to URIs youdesign and provide to the URL routing subsystem the framework provides.This is a bit different from traditional ASP.NET, in which URLs are mappeddirectly to disk-based files.

Chapter 7: Building REST Ser vices Using ASP.NET MVC Framework278

Page 46: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

The MVC framework has the capability to differentiate controlleractions based on HTTP method by judicious application of the ..� �9�/F�attribute, and you can disambiguate the action method names using the .�3&'6�� attribute.

The service logic itself is considered model code. The model in MVCterms is where the data access and business logic for your Web applicationis properly placed. I elected not to use a view to generate the HTML theservice returned, but you certainly could if you chose to do so.

It’s at this point you might notice a pattern emerging. When workingwith pure ASP.NET, you need to provide quite a bit of infrastructure and“glue” logic. With the MVC framework, quite a bit of the infrastructure isprovided for you. It’s more a matter of understanding what the frameworkprovides and how to best fit your service into that framework.

The next chapter, however, shows you how to use the Windows Com-munication Foundation (WCF) to implement RESTful services, and byusing WCF you implement even less boilerplate infrastructure, allowingyou to concentrate nearly entirely on the core service functionality. WCF isalso very much more configurable, allowing you to tailor your service’sbehavior even after it has been deployed.

Where Are We? 279

Page 47: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Index

413

Symbols100 Continue, 391101 switching protocols, 3921xx information codes, 391-392200 OK, 391-392200-level codes, 50201 Created, 392202 Accepted, 392203 non-authoritative information, 392204 No Content, 393205 Reset content, 393206 Partial content, 3932xx success codes, 392-393300 multiple choices, 393300-level codes, 50301 Moved permanently, 394302 Found, 394303 See other, 394304 Not modified, 395305 Use proxy, 395306 Unused, 395307 Temporary redirect, 3953xx redirection codes, 393-395400 Bad request, 391, 396400-level codes, 50401 Unauthorized, 396402 Payment required, 397403 Forbidden, 397-398

404 Not found, 391, 398-400405 Method not allowed, 400406 Not acceptable, 400407 Proxy authentication required, 400408 Request timeout, 401409 Conflict, 391, 401410 Gone, 391, 401411 Length required, 401412 Precondition failed, 402413 Request entity too large, 402414 Request URI too long, 402415 Unsupported media type, 403416 Requested range not satisfiable, 403417 Expectation failed, 4034xx client errors, 396-398, 400-403500 Internal server error, 391, 404,

408-411500-level response codes, 50501 Not implemented, 404502 Bad gateway, 405503 Service unavailable, 405504 Gateway timeout, 406505 Http version not supported, 4065xx server errors, 403-411

AAccept, HTTP headers, 51Accept*, 409

Page 48: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Accept-Encoding, HTTP headers, 51Accept-Language, HTTP headers, 51accepting HTTP methods, ASP.NET

MVC (model-view-controller), 252-254

account management, Azure, 377-378AccountController, 257AcquireRequestState, 181ActionName attribute, 262ActionResult, 251AddImages method, 119-120addressability

RESTful services, 23URI and, 65-68

addresses, Web addresses, 283-284schemes, 283

ADO.NET Data Servicesdefining, 311-315metadata, 315-316overview, 310-311service endpoints, 316-325

AJAX (Asynchronous JavaScript andXML), 125

AnonymousAuthenticationModule, 199anti-patterns, 59

caches, misusing, 62cookies, 62GET tunneling, 59-60hypermedia, lack of support, 63-64misused content types, 60-61POST tunneling, 60self-descriptions, lack of, 64status codes, 61-62

application state, RESTful services, 24application tracing, 266application-based clients, .NET Services

Access Control Service, 367-371client application code, 371-376

ApplicationHost, ASP.NET, 208approval process, Azure Comments

Service, 351ASP.NET, 205-206

ApplicationHost, 208hosting in console applications,

206, 209

HttpHandler, 210-211BlogService handler, 216-228designing blog services, 211-214service security, 215-216Web.config, 228-229

integrating with WCF (WindowsCommunication Foundation),295-298

Main method, 208PageHandlerFactory, 246RESTful clients, 229-230RESTful services, 35sample .aspx files, 208ScriptManager, 143securing services, 231-232security

AuthorizationManager, 240-242HttpApplication class, 237-239provider model, 232-236

security and, 199-202URI, 228

ASP.NET MVC (model-view-controller), 245

CodeXRC, 258-260CodeXRC service classes, 264-273CodeXRC service clients, 276-278CodeXRCController, 261-264URL mapping, 260-261

controller actions, 251-252HTTP methods, accepting, 252-254model, 256security, 256-258URL routing, 249-251views, 255-256

ASP.NET REST architecturalconsiderations, 381-388

ASP.NET XML Web Services (.asmx),JavaScript, 142

.aspx files (sample), 208AsyncCallbackException, 114Asynchronous JavaScript and XML

(AJAX), 125asynchronous methods, Silverlight, 149asynchronous programming

techniques, WinForms, 110

Index414

Page 49: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

asynchronous response handling, 114ATOM (Atom Syndication Format), 18

Azure Comment service atom feed, 368

ATOM feed listings, 363Atom feeds, supporting with WCF

(Windows CommunicationFoundation), 302-310

Atom Syndication Format, 375ATOM, 18

attributesDataContractSerializer, 107System.Xml.Serialization, 103

AuthenticateRequest, 180, 237

authenticationHTTP Basic Authentication, 33HTTP headers, HTTP Basic

Authentication, 57-59RESTful services, 31-33

authentication modules, 199authentication tokens, 345AuthenticationType, 235authority, 70authorization, 201

HTTP headers, 51RESTful services, 31-33

AuthorizationManager, ASP.NETsecurity, 240-242

Authorize attribute, 257-258AuthorizeRequest, 180Azure, 340-341

account management, 377-378CardSpace, 349cookies, 350credential requests, 365.NET Services. See .NET Services

Azure Access Control Manager, 378Azure Comment service atom feed, 368Azure Comments Service, 351

approval process, 351channel definition, 352CommentModel, 356-357

configuring, 361-362DTOs, 353GetAllComments, 353-354GetAllCommentsFormatter, 354-355GetSyndicatedComment, 355hosting, 359-361implementing, 352PUT, 352SaveComment, 357-358

BBasic Authentication, HTTP headers,

57-59BasicAuthenticationModule, 199BeginGetRequestStream, Silverlight, 154BeginRequest, 180Berners-Lee, Tim, 3best practices for REST, 407binding, 282bindings, WebHttpBinding, 288-290blog services, designing, HttpHandler

(ASP.NET), 211-214BlogEntryItem, 225BlogService handler, HttpHandler

(ASP.NET), 216-228BlogService handler method, 218BodyStyle property

(WebMessageBodyStyle), 290browser-based clients, .NET Services

Access Control Service, 363-367Bustamante, Michelle, 282

C.cache, 186cache modules, 182Cache-Control, HTTP headers, 51CacheItem, 184cacheLock, 187caches, misusing caches (anti-

patterns), 62CacheStream, 184

Index 415

Page 50: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

caching HTTP headers, 53-56CardSpace, 349-350CardSpace manager, 366CertificateMappingAuthentication-

Module, 200CGI (Common Gateway Interface), 3channel definition, Azure Comments

Service, 352choosing ASP.NET REST architectural

considerations, 381-388classes

BlogEntryItem, 225-226CacheItem, 183CacheStream, 184CodeXRC link builder, 270CodeXRCServiceBase, 264CommentModel, 356DataServiceKeyAttribute, 315-316HttpApplication, 237-239ImageItem, 284-285ImageUser, 311-312, 315OperationContractAttribute, 286-287ServiceContractAttribute, 286-287ServiceIdentity, 236ServiceUser class, 235-236TraceSource, 330-334TransportBindingElement, 288UserDataService, 313-315WebGetAttribute, 289WebInvokeAttribute, 289WebOperationContext, 293WebScriptServiceHostFactory, 295WebServiceHostFactory, 295

client access, .NET Servicesprogramming model, 350

client application code, application-based clients (.NET Services AccessControl), 371-376

clientaccesspolicy.xml, 162clients

ASP.NET, 229-230service clients. See service clients

closing streams, 155cloud services, 340

CLR (Common Language Runtime), 149CodeXRC, 256-260

CodeXRCController, 261-264service classes, 264-276service clients, 276-278URL mapping, 260-261XML, 268

CodeXRC client, 276-278CodeXRC link builder class, 270CodeXRCAuxServices

RenderErrorForbidden method, 273CodeXRCController, 261-264CodeXRCDataAccess LlistProjects

method, 274CodeXRCGetService ExecuteResult

method, 265-266CodeXRCPutService CreateResource

method, 271-272CodeXRCPutService ExecuteResult

method, 271CodeXRCServiceBase class, 264CollectionDataContractAttribute, 107COMException, 114Comment Model InsertComment

method, 356CommentModel, Azure Comments

Service, 356-357Common Gateway Interface (CGI), 3Common Language Runtime (CLR), 149Common Object Request Broker

Architecture (CORBA), 7Community Technology Preview

(CTP), 340conditional GET, HTTP headers, 53-56configuring

Azure Comments Service, 361-362TraceSources, 331-332WCF message logging, 336

connecting RESTful services, 31content negotiation, 28-29content types, misused content types

(anti-patterns), 60-61Content-Encoding, HTTP headers, 51Content-Language, HTTP headers, 51

Index416

Page 51: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Content-Length, HTTP headers, 52Content-Type, HTTP headers, 52Content-Type headers, 29contracts, 284Control.Invoke, 114controller actions, ASP.NET MVC,

251-252cookies

anti-patterns, 62ASP.NET MVC, 257Azure services, 350RESTful services, 26-27

CORBA (Common Object RequestBroker Architecture), 7

CreateRequest method, 118credential requests, Azure, 365credentials, WebRequest, 117Critical traces (WCF), 332cross-domain, 410cross-side scripting (XSS), 141CTP (Community Technology

Preview), 340

Ddata, reading, 90-92

DataContractSerializer, 106-109XDocument, 99-102XmlDocument, 93-99XmlSerializer, 102-106

data access layer, CodeXRC, 273-276data transfer objects (DTO), 275DataContract, 108

Silverlight, 153DataContractAttribute, 107DataContractJsonSerializer, Silverlight,

153, 157DataContractSerializer, 106-109

attributes, 107Silverlight, 159

DataMemberAttribute, 107DataServiceKeyAttribute class, 315-316DCOM (Distributed Component Object

Model), 7debugging Visual Studio, 190-191

defining ADP.NET Data Services, 311-315

DELETEWinForms, 121XHR, 138-139

DELETE method, HTTP, 45dereferencing, 69deserialization, 91designing blog services, HttpHandler

(ASP.NET), 211-214desktop applications, 87DHCP (Dynamic Host Configuration

Protocol), 342diagnostics

failed request tracing, 195-199HttpContext.Trace, 192-193System.Diagnostics, 193-195Visual Studio, 190-191WCF (Windows Communication

Foundation) diagnosticsevent logs, 328message logging, 334-336performance counters, 325-327tracing, 330-334WMI (Windows Management

Instrumentation), 328-330DigestAuthenticationModule, 200DispatchAddBlogItem method, 222DispatchAddBlogList method, 222DispatchGetBlogList method, 220Dispose, implementing HTTP

modules, 180Distributed Component Object Model

(DCOM), 7DNS (Domain Name Service), 343DTOs (data transfer objects), 275

Azure Comments Service, 353Dynamic Host Configuration Protocol

(DHCP), 342

EEndGetRequestStream, Silverlight, 154EndRequest, 181

Index 417

Page 52: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

EntryLink property, 227EnumMemberAttribute, 107error information, returning with

CodeXRC, 273Error traces (WCF), 332ETags, 390

HTTP headers, 52-56event logs in WCF (Windows

Communication Foundation), 328Execute button handler, 375ExecuteResult, 271$expand query string, 312

Ffabric, 340failed request tracing, 195-199failedCallback, 145FailedRequestTracing module, 195Fielding, Roy, 7-9FileAuthorization, 201Filter, 184$filter query string, 312Firebug, JSON content, 155Flash policy files, 410FormsAuthentication, 200fragments, 70framing bits, 167

GGenerateETagValue, 55GET method

conditional GET, 53HTTP, 42

GET tunneling, anti-patterns, 59-60GetAllComments, Azure Comments

Service, 353-354GetAllCommentsFormatter, Azure

Comments Service, 354-355GetImageHead method, 291-293GetImagesForUser method, 296-297GetImagesForUserHead method,

291-292

GetRequestStream, 149GetSyndicatedComment, Azure

Comments Service, 355guiding principles for RESTful services,

20-21

HHEAD action, CodeXRCController,

261-262HEAD method, HTTP, 44headers

Content-Type, 29HTTP content type headers, 29HTTP headers, 50

Accept, 51Accept-Encoding, 51Accept-Language, 51Authorization, 51Cache-Control, 51caching, 53-56conditional GET, 53-56Content-Encoding, 51Content-Language, 51Content-Length, 52Content-Type, 52ETag, 52-56Host, 52If-Match, 52If-Modified-Since, 52If-None-Match, 52If-Range, 52If-Unmodified-Since, 52Last-Modified, 52Location, 52User-Agent, 53WWW-Authenticate, 53

hierarchical identification, URI, 70-71Host, HTTP headers, 52hosting

ASP.NET in console applications, 209Azure Comments Service, 359-361

HTMLrender methods, 269Silverlight, 158

Index418

Page 53: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

HTTP (Hyper Text Transfer Protocol), 5,39-40, 283

content type header values, 29messages, 40REST, 23

HTTP Accept header, 409HTTP Basic Authentication, 33, 57-59

securing services, ASP.NET, 231WinForms, 116

HTTP Digest Authentication, 57HTTP handlers, implementing in IIS

messaging pipeline, 173-180HTTP headers, 50

Accept, 51Accept-Encoding, 51Accept-Language, 51Authorization, 51Cache-Control, 51caching, 53-56conditional GET, 53-56Content-Encoding, 51Content-Language, 51Content-Length, 52Content-Type, 52ETag, 52-56Host, 52HTTP Basic Authentication, 57-59If-Match, 52If-Modified-Since, 52If-None-Match, 52If-Range, 52If-Unmodified-Since, 52Last-Modified, 52Location, 52User-Agent, 53WWW-Authenticate, 53, 57-59

HTTP Location header, 409HTTP methods, 42

accepting in ASP.NET MVC, 252-254DELETE method, 45GET method, 42HEAD method, 44idempotency and, 43-44

OPTIONS method, 42POST method, 46-47

idempotency, 48-49POST responses, 47-48

PUT method, 45RESTful interpretations, 41safety and, 43-44

HTTP modules, implementing in IISmessaging pipeline, 180-190

HTTP response codes, 49-50HTTP status codes, 389

1xx informational codes, 391-3922xx success codes, 392-3933xx redirectopm codes, 393-3954xx client errors, 396-4035xx server errors, 403-406setting, 390-391

http.sys, 34, 166-169HttpListener, 35

HttpApplication class, ASP.NETsecurity, 237-239

HttpApplication instance, 180HttpCfg.exe, 169HttpContext, 176HttpContext.Trace, 192-193HttpExerciser, 82-84HttpHandler, ASP.NET210-211

blog services, designing, 211-214BlogService handler, 216-222, 224-228service security, 215-216Web.config, 228-229

HttpListener, 35, 80-81HttpModule, 238HttpRequest, 176HttpResponse, 176HttpStatusCode.Accepted, 392HttpStatusCode.Ambiguous, 393HttpStatusCode.BadGateway, 405HttpStatusCode.BadRequest, 391, 396HttpStatusCode.Conflict, 391, 401HttpStatusCode.Continue, 391HttpStatusCode.Created, 392

Index 419

Page 54: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

HttpStatusCode.ExpectationFailed, 403HttpStatusCode.Forbidden, 397-398HttpStatusCode.Found, 394HttpStatusCode.GatewayTimeout, 406HttpStatusCode.Gone, 391, 401HttpStatusCode.HttpVersionNot-

Supported, 406HttpStatusCode.InternalServerError,

391, 404HttpStatusCode.LengthRequired, 401HttpStatusCode.MethodNot-

Allowed, 400HttpStatusCode.Moved, 394HttpStatusCode.Moved-

Permanently, 394HttpStatusCode.MultipleChoices, 393HttpStatusCode.NoContent, 393HttpStatusCode.NonAuthoritative-

Information, 392HttpStatusCode.NotAcceptable, 400HttpStatusCode.NotFound, 391, 398-400HttpStatusCode.NotImplemented, 404HttpStatusCode.NotModified, 395HTTPStatusCode.OK, 391-392HttpStatusCode.PartialContent, 393HttpStatusCode.PaymentRequired, 397HttpStatusCode.PreconditionFailed, 402HttpStatusCode.ProxyAuthentication-

Required, 400HttpStatusCode.Redirect, 394HttpStatusCode.RedirectKeepVerb, 395HttpStatusCode.RedirectMethod, 394HttpStatusCode.RequestedRangeNot-

Satisfiable, 403HttpStatusCode.RequestEntityToo-

Large, 402HttpStatusCode.RequestTimeout, 401HttpStatusCode.RequestUriToo-

Long, 402HttpStatusCode.ResetContent, 393HttpStatusCode.SeeOther, 394HttpStatusCode.Service-

Unavailable, 405

HttpStatusCode.SwitchingProtocol, 392HttpStatusCode.Temporary-

Redirect, 395HttpStatusCode.Unauthorized, 396HttpStatusCode.UnsupportedMedia-

Type, 403HttpStatusCode.Unused, 395HttpStatusCode.UseProxy, 395HttpSysCfg.exe, 203Hyper Text Transfer Protocol. See HTTPhypermedia, 3

lack of support for hypermedia, anti-patterns, 63-64

hypermedia links, 63

IICommentService, 353idempotency

HTTP methods and, 43-44POST, 48-49

identification, URI, 69-70hierarchical identification, 70-71

Identity property, 234IETF (Internet Engineering Task

Force), 389If-Match, 402

HTTP headers, 52If-Modified-Since, HTTP headers, 52If-None-Match, 402

HTTP headers, 52If-Range, HTTP headers, 52If-Unmodified-Since, 402

HTTP headers, 52IHttpHandler, 173-175IIdentity property, 234IImageService interface, 285-286IIS (Internet Information Server 7.0), 34,

165-167integrating with, 170-171

IIS messaging pipeline, 171-172IIS messaging pipeline. See IIS

messaging pipeline

Index420

Page 55: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

resource for more information, 202-203security and, 199-202

IIS messaging pipeline, 171-172HTTP handlers, implementing,

173-180HTTP modules, implementing, 180-190

IIS worker process, 170iis.net, 202IISCertificateMappingAuthentication-

Module, 200ImageItem, 89

reading data, 90-92XHR, 136

ImageItem class, 284-285ImageManager, XHR, 138ImageManager service, building

ADO.NET Data Servicesdefining, 311-315metadata, 315-316overview, 310-311service endpoints, 316-325

ASP.NET integration, 295-298Atom support, 302-310IImageService interface, 285-286ImageItem class, 284-285ImageUser class, 311, 315JavaScript files, 293-294OperationContractAttribute class,

286-287RSS support, 302-310ServiceContractAttribute class, 286-287URL rewriters, 298-301UserDataService class, 313-315WCF REST stack

GetImageHead method, 291-293GetImagesForUserHead method,

291-292WebHttpBinding binding, 288-290WebOperationContext class, 293

imagesLookupImages, XHR, 133-135Photo Client’s DeleteImage and

DeleteResponse, 121-122

retrievingwith Silverlight, 160with XHR, 132-133

ImagesResponse, Silverlight, 152ImageUser class, 311-315impersonation, 170Information level traces (WCF), 333infoset, XML, 94init, implementing HTTP modules, 180installing Photo Service, 110instrumentation, 192-193integrating with IIS, 170-171

IIS messaging pipeline, 171-173interfaces, IImageService, 285-286Internet Engineering Task Force

(IETF), 389Internet Protocol (IP), 167Invoke, 114invoking JavaScript methods, from

Silverlight, 161IP (Internet Protocol), 167IP addresses, 167IPSec (IP Security), 31IPv6, 343IsReusable, 173

J-KJavaScript

calling existing JavaScript withSilverlight, 161-162

WCF, 142-148page level handlers, 145ScriptManager, 143ScriptManagerProxy, 144

xxx, 145JavaScript files, generating with WCF

(Windows CommunicationFoundation), 293-294

JavaScript methods, invoking fromSilverlight, 161

JQuery, 139

Index 421

Page 56: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

JQuery UI, 139JSON (JavaScript Object Notation), 90

designing blog services, HttpHandler(ASP.NET), 213

render methods, 269Silverlight, 153-158

JsonImageService, 151

LLanguage Integrated Query (LINQ), 99Last-Modified, HTTP headers, 52linking RESTful services, 31LINQ (Language Integrated Query),

99-100listings

AddImages method, 119-120Asynchronous response handling, 114Azure Comment service channel

definition, 352BlogEntryItem class, 225-226BlogService AuthModule basic

HttpModule implementation, 238BlogService primary handler

methods, 216BlogService Web.config

handler/module settings, 229BlogService’s DispatchAddBlogItem

method, 222-224BlogService’s DispatchGetBlogList

method, 220BlogService’s TemplateTable property,

217-218BlogService’s/Blog handler

method, 218BlogService’s/Blog/{BlogID} handler

method, 219-220Browser-independent XHR

instantiation, 129-130CacheItem class, 183CacheStream, 184Calling MusicBrainz service, 19

Calling the NDFD ZIP Codeconversion service, 13

The client application Execute buttonevent handler, 373-374

The client applicationPushCommentItem method, 376

The client applicationQueryAuthenticationToken, 371-372

CodeXRC link builder class, 270CodeXRCAuxServices

RenderErrorForbidden method, 273

CodeXRCController HTTP HEADaction, 261-262

CodeXRCController HTTP PUT action,263-264

CodeXRCDataAccess ListProjectsmethod, 274

CodeXRCGetService ExecuteResultmethod, 265-266

CodeXRCPutService CreateResourcemethod, 271-272

CodeXRCPutService ExecuteResultmethod, 271

CodeXRCServiceBase class, 264Comment data transfer object, 353The Comment service host application

configuration, 361-362Comment service SaveComment

method implementation, 357-358CommentModel InsertComment

method, 356CreateRequest method, 118GetAllComments implementation, 354GetAllCommentsFormatter helper

method, 354GetSyndicatedComment helper

method, 355The host console application’s Main

method, 359-360Hosting ASP.NET in a console

application, 206

Index422

Page 57: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

HTTP Response to ZIP Codeconversion for code 20004, 10

ImageItem class, 91ImageItem serialized as JSON, 90ImageItem serialized as XML, 90ImageItem with data contract

attributes applied, 108ImageItem with XML serialization

attributes applied, 105Initiating the JSON-based “my

images” service request, 156Initiating the JSON-based “upload

photo” Service request, 160Interpreting the JSON-based service

response, 157-158Invoking a JavaScript method from

Silverlight, 161The Model class’s QueryBlog

method, 225OnAuthenticateRequest method

implementation, 238Photo Client asynchronous user

account creation, 113Photo Client Login button click

handler, 117Photo Client’s ReadResponse

method, 120Photo Client’s ShowImages method

(WPF version), 123Photo Client’s WCF-based

LookupImages method, 146Photo Client’s WCF-based SaveData

method, 147-148PhotoWebXHR Delete method, 139PhotoWebXHR SaveData method, 140Populating UriTemplateTable, 175-176Preparing image files for transmission

to the photo service, 159The preserialized ImageItem

resource, 92Process Service OutputProcessList and

OutputProcessInfo, 177-178Process Service ProcessRequest

method, 177

ProcessCacheModule ASP.NETmodule implementation, 186

ProcessInfoBasic and ProcessInfo, 174The project data transfer object, 275Reading and consuming XML using

XDocument and XLINQ, 100Reading and consuming XML

using XDocument and XLINQfailover, 101

Reading and consuming XML usingXMLDocument and XPath, 97-98

RenderXML method, 268ResolveRequestCacheHandler

method, 187-188Retrieving a single photo instance, 160Sample .aspx page, 209SerializationSampler Main method, 92ServiceIdentity class, 236ServiceUser class, 235-236Silverlight application’s

ImagesResponse, 152Silverlight application’s Load Friend

button click, 152Silverlight application’s Load My

Images button click handler, 154Simplified UriTemplate use, 73Simplified UriTemplateTable use, 76UpdateRequestCacheHandler

method, 188Using UriBuilder, 79XHR OnReadyStateChange event

handling, 136-138LoadFriend_Click method, 151Location, HTTP headers, 52logging, 192

in WCF (Windows CommunicationFoundation)

event logs, 328message logging, 334-336

login button click handler, 117LogRequest, 181LookupImages, 132

WCF, 146XHR, 133-135

Lowy, Juval, 282

Index 423

Page 58: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

MMain method

ASP.NET, 208hosting Azure Comments Service, 359

MapRequestHandler, 181MD5 (Message Digest 5), 200MemoryStream, 184Message Digest 5 (MD5), 200message logging in WCF (Windows

Communication Foundation), 334-336

messages, HTTP, 40metadata, adding, 315-316methods

GetImageHead, 291-293GetImagesForUser, 296-297GetImagesForUserHead, 291-292

Microsoft AJAX (MS-AJAX), 127Microsoft Message Queue (MSMQ), 12model-view-controller (MVC). See

ASP.NET MVCmodels, ASP.NET MVC, 256modules

authentication modules, 199authorization modules, 201FailedRequestTracing module, 195HTTP modules, implementing in IIS

messaging pipeline, 180-190Moonlight, 149MS-AJAX (Microsoft AJAX), 127MSMQ (Microsoft Message Queue), 12MusicBrainz, 16-19, 63-64

calling the service, 19MVC (model-view-controller). See

ASP.NET MVCmvolo.com, 202

NNAT (network address translation), 343

.NET Services, 347NDFD (National Digital Forecast

Database), 9-10

NDFD ZIP Code conversion service,calling, 13

.NEThttp.sys, 34HttpListener, 35schemas, 103XML markup, 91

.NET 3.5, LINQ, 99

.NET Access Control Service, 344-346

.NET Service Bus, 346-347

.NET Services, 340-344.NET Access Control Service, 344-346.NET Service Bus, 346-347.NET Workflow Service, 347programming model, 347-348

client access, 350service initiation, 349

.NET Services Access Control Service,service clients, 363

application-based clients, 367-376browser-based clients, 363-367

.NET Workflow Service, 347network address translation. See NATNetworkCredentials, 350notepad.exe, process information, 179NTLM (Windows NT LAN

Manager), 233NullReferenceException, 149

OOAuth tokens, 142OnAuthenticateRequest, 238OpenFileDialog, Silverlight, 158OpenSocial, 142OperationContractAttribute class,

286-287OPTIONS method, HTTP, 42$orderby query string, 312Outlook, 87Outlook Web Access, 87OutputProcessInfo, 177-178OutputProcessList, 177-178Ozzie, Ray, 341

Index424

Page 59: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

Ppage level handlers, WCF

(JavaScript), 145Page method, 250PageHandlerFactor, 246PartialContent, 393paths, 70performance, WCF, 383-384performance counters (WCF), 325-327Photo Client, WinForms, 110-122

authentication, 116CreateRequest method, 118DELETE, 121WebRequest, 117

Photo Service, installing, 110photos, REST services and, 89PhotoWebXHR, 132plain old XML (POX), 18plug-ins, Firebug (JSON content), 155populating UriTemplateTable, 175-176POST method, HTTP, 46-47

Idempotency, 48-49POST responses, 47-48

POST responses, 47-48POST tunneling, anti-patterns, 60PostAcquireRequestState, 181PostAuthenticateRequest, 180PostAuthorizeRequest, 180PostLogRequest, 181PostMapRequestHandler, 181PostReleaseRequestState, 181PostRequestHandlerExecute, 181PostResolveRequestCache, 181PostUpdateRequestCache, 181POX (plain old XML), 18PreRequestHandlerExecute, 181PreSendRequestContent, 182PreSendRequestHeaders, 182project data transfer objects, 275process information for

notepad.exe, 179ProcessCacheModule, ASP.NET

module, 186

ProcessInfo, 174ProcessInfoBasic, 173-174ProcessRequest, 173

implementing HTTP handlers, 177programming models, .NET Services,

347-348client access, 350service initiation, 349

protocolsDHCP, 342HTTP, 283IP (Internet Protocol), 167SMTP, 12SOAP. See SOAPswitching protocols, 101, 392TCP (Transmission Control

Protocol), 167wire protocols, 4-5

provider model, ASP.NET security, 232-236

PushCommentItem method, 376PUT

Azure Comments Service, 352CodeXRCController, 263-264HTTP, 45

Qqueries, 70query strings, 312QueryAuthenticationToken, 373QueryAuthenticationToken method,

371-372

RReaderWriterLock, 186reading data, 90-92

DataContractSerializer, 106-109XDocument, 99-102XmlDocument, 93-99XmlSerializer, 102-106

ReadResponse method, 120

Index 425

Page 60: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

readyState, XHR, 135-138realms, WWW-Authenticate, 57relay, .NET Service Bus, 346RelayChannel, 347-348ReleaseRequestState, 181RenderXML method, 268Representational State Transfer.

See RESTrepresentations of resources, RESTful

services, 27content negotiation, 28-29URI design, 29-30

RequestFormat property(WebMessageFormat), 290

reservations, 166ResolveRequestCache, 181, 185ResolveRequestCacheHandler method,

187-188resources, 408

creating wtih XML, 271-273representations of resources, 27

content negotiation, 28-29URI design, 29-30

URIs, 23, 408ResponseFormat property

(WebMessageFormat), 290REST (Representational State Transfer),

1, 8, 14-15, 386best practices, 407-411HTTP, 23SOAP versus, 385URLs, 16

RESTful services, 20addressability and the URI, 23connecting, 31cookies, 26-27guiding principles for, 20-21linking, 31MusicBrainz, 16-19representations of resources, 27

content negotiation, 28-29URI design, 29-30

resources for, 21-22

security, 31-33types of states, 23-26

retrieving images with Silverlight, 160returning error information with

CodeXRC, 273RFC 2616, 407RFC 2626, 53RFC 3986, URIs, 68RPC (remote procedure calls), 5RPC method serialization, 6RSS feeds, supporting with WCF

(Windows CommunicationFoundation), 302-310

SSaaS (Software as a Service), 346safety, HTTP methods and, 43-44SAML (Security Assertion Markup

Language), 345SaveComment, Azure Comments

Service, 357-358SaveData

WCF, 147-148XHR, 140

schemas, 70, 283.NET, 103

ScriptManager, 143ScriptManagerProxy, 143

JavaScript, 144Scripts, 143SDDLParse, 203Secure Sockets Layer (SSL), 31Secure Token Service (STS), 344securing services (ASP.NET), 231-232security

ASP.NET, 199-202, 256-258AuthorizationManager, 240-242HttpApplication class, 237-239provider model, 232-236

authorization, authorization modules, 201

IIS, 199-202

Index426

Page 61: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

RESTful services, 31-33services, HttpHandler (ASP.NET),

215-216XHR and, 141-142

Security Assertion Markup Language(SAML), 345

self-descriptions, anti-patterns, 64service classes, CodeXRC, 264-273

data access layer, 273-276returning error information, 273

service clientsCodeXRC, 276-278.NET Services Access Control

Service, 363application-based clients, 367-376browser-based clients, 363-367

service endpoints, adding, 316-325service initiation, .NET Services

programming model, 349service response, JSON-based, 157service versioning, 408ServiceContractAttribute class, 286-287ServiceIdentity class, 236Services, 143services

Azure Comments Service. See AzureComments Service

cloud services, 340ImageManager, building

ADO.NET Data Services, 310-325ASP.NET integration, 295-298Atom support, 302-310IImageService interface, 285-286ImageItem class, 284-285ImageUser class, 311, 315JavaScript files, 293-294OperationContractAttribute class,

286-287RSS support, 302-310ServiceContractAttribute class,

286-287URL rewriters, 298-301

UserDataService class, 313-315WCF REST stack, 288-293securing (ASP.NET), 231-232

security, HttpHandler (ASP.NET), 215-216

ServiceUser class, 235-236session state, RESTful services, 24ShowImages method, WPF version,

123-124Silverlight, 127, 149

asynchronous methods, 149BeginGetRequestStream, 154calling existing JavaScript, 161-162DataContract, 153DataContractJsonSerializer, 153, 157DataContractSerializer, 159EndGetRequestStream, 154HTML, 158ImagesResponse, 152invoking JavaScript method, 161JSON, 153-158JsonImageService, 151Load Friend button click handler, 152Load My Images, 154NullReferenceException, 149OpenFileDialog, 158retrieving images, 160UI, 150XmlImageService, 151

Silverlight files, 410Simple Mail Transfer Protocol

(SMTP), 12Simple Object Access Protocol

(SOAP), 4$skip query string, 312Smith, Justin, 282SMTP (Simple Mail Transfer

Protocol), 12SOAP (Simple Object Access Protocol),

4-7, 385REST versus, 385

Software as a Service (SaaS), 346

Index 427

Page 62: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

solution names, 346SSL (Secure Sockets Layer), 31startup screen, WinForms, 111states, RESTful services, 23-26status codes

anti-patterns, 61-62setting, 390-391

Stream, 184streams, closing, 155STS (Secure Token Service), 344succeededCallback, 145switching protocols, 101, 392System.Diagnostics, 193-195System.Diagnostics.TraceSource, 193System.Net.WebRequest, 112, 149

WinForms, 109System.Web.UI.ScriptManager-

Proxy, 143System.Xml.Ling.XDocument, 91System.Xml.Serialization, attributes, 103System.Xml.XmlDocument, 91

TTCP (Transmission Control

Protocol), 167TemplateTable property,

BlogService, 217text/plain, 61text/xml, 60ThreadPool, 119threads, 119$top query string, 312TraceListeners, 193TraceSource class, 330-334tracing, 194, 266

failed request tracing, 195-199in WCF (Windows Communication

Foundation), 330-334transcription, URI, 68-69Transmission Control Protocol

(TCP), 167

Transport Security Layer (TSL), 31TransportBindingElement class, 288TSL (Transport Security Layer), 31tunneling

GET, anti-patterns, 59-60POST, anti-patterns, 60URI, 66

txt/html, 60

UUDDI (Universal Description Discovery

and Integration), 66UI (user interface), 88

Silverlight, 150WinForms, 109

Uniform Resource Identifier. See URIUniform Resource Locator. See URLUnity, 8Universal Description Discovery and

Integration (UDDI), 66Universal Resource Name (URN), 65UpdateRequestCache, 181, 185UpdateRequestCacheHandler

method, 188URI (Uniform Resource Identifier),

39, 64addressability and, 65-68ASP.NET, 228hierarchical identification, 70-71resources, 408RESTful services, 23RFC 3986, 68separating identification from

interaction, 69-70transcription, 68-69tunneling, 66UriBuilder, 79-80UriTemplate, 71-74UriTemplateMatch, 71-74UriTemplateTable, 74-79

URI design, representation ofresources, 29-30

Index428

Page 63: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

UriBuilder, 79-80UriTemplate, 71-74UriTemplate property (String), 290UriTemplateMatch, 71-74UriTemplateTable, 74-79

Populating, 175-176URL (Uniform Resource Locator), 64URL encoding, 19URL mapping, CodeXRC, 260-261URL rewriters, adding with WCF

(Windows CommunicationFoundation), 298-301

URL routing, ASP.NET MVC, 249-251UrlAuthorization, 201UrlAuthorizationModule, 201UrlRoutingModule, 249URN (Universal Resource Name), 65user interface (UI), 88User-Agent, HTTP headers, 53UserDataService class, 313-315

VVerbose traces (WCF), 333views, ASP.NET MVC, 255-256Virtual Private Network (VPN), 31Visual Studio, 190-191Volodarsky, Mike, 202

WW3SVC (World Wide Web Publishing

Service), 166Warning traces (WCF), 332WAS (Windows Process Activation

Service), 166WCF (Windows Communication

Foundation), 36addresses, 283-284bindings, 282

WebHttpBinding, 288-290contracts, 284

diagnosticsevent logs, 328message logging, 334-336performance counters, 325-327tracing, 330-334WMI (Windows Management

Instrumentation), 328-330ImageManager service, building

ADO.NET Data Services, 310-325ASP.NET integration, 295-298Atom support, 302-310IImageService interface, 285-286ImageItem class, 284-285ImageUser class, 311, 315JavaScript files, 293-294OperationContractAttribute class,

286-287RSS support, 302-310ServiceContractAttribute class,

286-287URL rewriters, 298-301UserDataService class, 313-315WCF REST stack, 288-293

JavaScript, 143-148page level handlers, 145ScriptManager, 143ScriptManagerProxy, 144

LookupImages method, 146.NET Services, 347overview, 281-282performance, 383-384SaveData method, 147-148

WCF channels, 347Web addresses, 283-284

schemes, 283Web Service Description Language

(WSDL), 4, 385Web services, 9-14

introduction to, 88-90NDFD. See NDFD

Web.config, HttpHandler (ASP.NET),228-229

WebException, 113

Index 429

Page 64: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

WebGetAttribute class, 289WebHttpBinding binding, 288-290WebHttpRelayBinding, 362WebInvokeAttribute class, 289WebOperationContext class, 293WebRequest, Credentials, 117WebRequest.Create, 112WebResponse, WinForms, 109WebScriptServiceHostFactory class, 295WebServiceHost, Azure Comments

Service, 359-361WebServiceHostFactory class, 295wildcard paths, 179Windows CardSpace manager, 366Windows Communication Foundation.

See WCFWindows Forms (WinForms), 87Windows Management Instrumentation

(WMI), 328-330Windows NT LAN Manager

(NTLM), 233Windows Presentation Foundation.

See WPFWindows Process Activation

Service, 165Windows Process Activation Service

(WAS), 166Windows XP SP3, http.sys, 168WindowsAuthentication, 200WindowsAuthenticationModule, 201WinForms

asynchronous programming, 110Photo Client, 110-116, 119-122

authentication, 116CreateRequest method, 118DELETE, 121WebRequest, 117

startup screen, 111System.Net.WebRequest, 109UI threads, 109

wire protocols, 4-5WMI (Windows Management

Instrumentation), 328-330World Wide Web Publishing Service

(W3SVC), 166

WPF (Windows PresentationFoundation), 9, 87, 122-124

ASP.NET Rest client applications, 229ShowImages method, 123-124

WS-*, 4, 7WS-I Monitor Tool Specification, 335WS-I.org Monitor Tool, 335WSDL (Web Service Definition

Language), 385WSDL (Web Service Description

Language)4WWW-Authenticate, 57-59

HTTP headers, 53

X-Y-ZX-MS-Identity-Token, 350, 369XDocument, 99-102XDocumentAlternate, 92XHR (XMLHttpRequest), 127-132

capabilities for, 130-131DELETE, 138-139ImageItem, 136ImageManager, 138LookupImages, 133, 135readyState, 135-138retrieving images, 132-133SaveData, 140security and, 141-142

xhr.onreadystatechange, 135-138XLINQ, 99XML, 4

Atom Syndication Format, 375CodeXRC, 268infoset, 94reading data, 92

DataContractSerializer, 106-109XDocument, 99-102XmlDocument, 93-99XmlSerializer, 102-106

resources, creating, 271-273XML LINQ (XLINQ), 99XML Schema Document, 103XML serialization, 92XmlArrayAttribute, 104

Index430

Page 65: Library of Congress Cataloging-in-Publication Dataptgmedia.pearsoncmg.com/images/9780321613257/samplepages/...model delivers the best balance of performance and ease of implementa-tion,

XmlArrayItemAttribute, 104XmlAttributeAttribute, 103XmlDocument, 93-99XmlElementAttribute, 103XmlEnumAttribute, 103XmlHttpRequest objects, 7XMLHttpRequest. (XHR), 127-132

capabilities for, 130-131DELETE, 138-139ImageItem, 136ImageManager, 138LookupImages, 133, 135readyState, 135-138retrieving images, 132-133SaveData, 140security and, 141-142

XMLHttpRequest.setRequestHeadermethod, 139

XmlIgnoreAttribute, 103XmlImageService, 151XmlNodeReader, 96XmlReader, 96XmlRootAttribute, 103XmlSerializer, 102-106XmlTypeAttribute, 103XPath, 95XSS (cross-side scripting), 141xxx, JavaScript, 145

Index 431