39,59 €
If you are a .NET developer who is looking for a simpler way to build services, this is the book for you. It will show you how to write fast, maintainable APIs that are a pleasure to use and maintain starting from the database to the client and everything in-between.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 441
Veröffentlichungsjahr: 2015
Copyright © 2015 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: January 2015
Production reference: 1190115
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78398-656-9
www.packtpub.com
Cover image by Jarosław Blaminsky (<[email protected]>)
Authors
Kyle Hodgson
Darren Reid
Reviewers
Phillip Haydon
Andreas Niedermair
Alex Pop
Jezz Santos
Commissioning Editor
Kunal Parikh
Acquisition Editor
Richard Brookes-Bland
Content Development Editor
Sumeet Sawant
Technical Editor
Vijin Boricha
Copy Editor
Sarang Chari
Project Coordinator
Danuta Jones
Proofreaders
Simran Bhogal
Maria Gould
Ameesha Green
Paul Hindle
Indexer
Mariammal Chettiyar
Graphics
Disha Haria
Production Coordinator
Alwin Roy
Cover Work
Alwin Roy
Kyle Hodgson is a software developer based in Toronto, Canada. He was working on full stack web development, but he fell in love with ServiceStack after finishing a large WCF project. He has led the development of several ambitious products for organizations ranging from small start-ups to Fortune 50 enterprises and has been invited to speak at several technology conferences about .NET and JavaScript. Having joined ThoughtWorks in 2012, Kyle is thrilled to be working with some of the smartest minds in software today. You can find his blog at http://www.kylehodgson.com.
I'd like to thank my wife, Lily, for her support during this project. I'd also like to thank ServiceStack creator Demis Bellot for his support while writing the book. Of course, I couldn't have done it without my friend and the book's co-author, Darren Reid.
Darren Reid is a .NET and JavaScript developer based in Canberra, Australia. He has worked primarily in large enterprise environments, building corporate web applications, and has also contributed to ServiceStack-related products. He received prizes for projects created for GovHack in 2012 and 2013, utilizing the ServiceStack framework. Darren is an accomplished open source advocate and blogger, and his work can be seen at www.layoric.org, where he blogs about advanced ServiceStack and AngularJS topics among other things.
I'd like to thank my wife, Kim, for her love and support. I'd also like to thank the book's co-author Kyle Hodgson for his tireless efforts, good advice, and encouragement during the writing of our book. A big thank you to ServiceStack creator Demis Bellot for making .NET developers' lives easier. Finally, thanks to the developers of my favorite games, which I intend to enjoy once this book is published.
Phillip Haydon is a Kiwi (New Zealander) who has spent the better part of the past 10 years traveling Asia during the day and coding furiously at night. He currently lives in Singapore, actively contributes to the NancyFX and SimpleAuthentication open source projects, and tries to maintain his own Sandra Snow blog engine.
I would like to thank all the owners and contributors of NancyFX and ServiceStack, my two favorite projects with awesome teams that have taught me so much. Love you all!
Andreas Niedermair, a kid of the 1980s, got his hands dirty with QBasic and pressing "Refresh" in Netscape Navigator to review his websites, which later got enhanced by backend processing by PHP.
With the release of .NET he fell in love with the Microsoft stack, which he uses in his day job in the logistics industry.
Andreas lives in Austria and enjoys the outdoors, traveling, his guitars, and a good whisky in front of his Kachelofen. You can contact Andreas at http://andreas.niedermair.name.
Alex Pop is a professional software developer with a university degree in computer engineering and 12 years of commercial experience building .NET applications.
He has worked for ISVs, building enterprise resource planning applications, content management systems, and insurance and financial software products. He is currently working in the higher education sector as a web application developer.
His developer blog at alexvpop.blogspot.co.uk contains technical articles around .NET, JavaScript, and various software engineering topics.
I would like to thank my wife and daughter for their patient support.
Jezz Santos is a highly experienced developer, educator, coach, and mentor for software product delivery organizations and delivery teams. He began his career as a software research engineer at Nokia in Finland and then moved into software product development in start-ups in New Zealand, followed by over a decade at Microsoft in Western Europe and the USA. His broad focus at Microsoft was improving the output of product development teams, with a specific focus on development automation technologies and making team development a more sustainable, humanizing, and cooperative experience.
Now, he focuses on catalyzing excellence in product development by building high-performance, collaborative development teams that apply and continuously improve the application of the principles of craftsmanship, XP, and lean thinking. Jezz is currently doing all of that and still cutting code as a founder of Mindkin—a new, lean, Wellington-based product development start-up. Jezz is highly motivated to help establish New Zealand as a renowned worldwide leader in creating software development companies and products by growing and developing the huge potential of the people there.
You can reach out to Jezz through LinkedIn: https://www.linkedin.com/in/jezzsa.
See what Jezz Santos has to say about his experience with working on ServiceStack until now:
"After building numerous products and educating numerous teams of people on the full Microsoft web stack since .NET beta, the discovery of ServiceStack was just what test-first product developers want as a highly usable, testable, flexible, robust, and performant framework. Much like many other frameworks developed in the last few years, the experience of applying ServiceStack to real product development is to experience far less friction and higher productivity than applying any of the Microsoft web technologies. There is real "magic" in there and it's careful crafted to be highly usable by developers. Huge credit is deserved by the creators of ServiceStack, Demis Bellot et al and the entire ServiceStack community supporting it, making the experience for ServiceStack product developers such a fine and complete one."
"This book will be a real good guide for developers for getting up to speed, for revealing some of ServiceStack's, secrets and how to get more from it in your new products!"
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.
In recent times, web service APIs have become one of the most important parts of developing web applications. ServiceStack offers .NET developers a powerful set of tools that are thoughtfully architected with a core focus on simplicity, developer experience, and performance. With tools ranging from database access and HTML generation, to logging, serialization, caching, and more, ServiceStack gives developers a fantastic experience in developing web applications.
In this book, we address many of ServiceStack's features, including an introduction to using them and solving problems faced by .NET developers building web applications.
Chapter 1, Configuration and Routing, covers the various configuration options and ways to set up routing using the ServiceStack framework. We will also learn how to set up your solution and projects in a way that promotes testability and reuse and how to get the most out of ServiceStack's built-in IoC functionality.
Chapter 2, Services and Data Transfer Objects, says that these concepts (services and data transfer objects) are at the core of building web services with ServiceStack. This chapter teaches you techniques to produce clean, testable web services and gives examples of some common usages. You will also be shown how to use request/response filters for advanced request processing and integration.
Chapter 3, Testing and Logging, shows the integration of logging via ServiceStack LogManager, integration with popular testing frameworks as well as patterns for continuous integration.
Chapter 4, Object Relational Mapping (OrmLite), covers some of the functionality OrmLite provides while using practical patterns to keep your code clean and maintainable. OrmLite is a lightweight object relational mapping framework that focuses on simplicity and performance.
Chapter 5, HTML and Form Data, shows the different tools that the ServiceStack framework gives developers to handle HTML generation and specific interactions on web pages.
Chapter 6, Filters and Validators, shows the versatility of ServiceStack filters for different uses, including integration, as well as validators to assist with HTML forms or API error messages.
Chapter 7, Security and Authentication, shows ServiceStack OAuth and other built-in security functionality as well as how to deal with custom authentication and integration with commonly used frameworks/systems.
Chapter 8, Working with Redis, teaches you how to get the most out of the Redis client provided and ServiceStack integration as well as setting up Redis and using it in different environments.
Chapter 9, Integrating with Other Technologies, covers integration with popular and common frameworks and technologies to highlight ServiceStack's power when used in conjunction with existing systems. The chapter also covers how to handle introducing ServiceStack into an established ASP.NET MVC and WebForms project.
Appendix A, Getting Started, takes you through creating a ServiceStack solution, walking you through the different parts. This will be useful for readers who don't have access to use the ServiceStack Visual Studio extension, ServiceStackVS.
Appendix B, Testing Locally, is a short guide on how to use Fiddler2 to route traffic of a different domain to IIS Express. Depending on your environment restrictions, this might help debug OAuth providers. This isn't needed to complete the recipes in this book.
While most examples simply require Visual Studio 2013 Community Edition or better, some recipes do use other technologies to illustrate integration with specific functionality within the ServiceStack framework. The following is a list of software required to use all the examples:
If you are a .NET developer who is looking for a simpler way to build services, this is the book for you. It will show you how to write fast, maintainable APIs that are a pleasure to use and maintain, starting from the database to the client and everything in between.
In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.
To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from: https://www.packtpub.com/sites/default/files/downloads/6569OS_ImageBundle.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the ErrataSubmissionForm link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.
In this chapter, we'll talk a bit about ServiceStack and we will present the following recipes:
ServiceStack is a .NET framework that makes it easy to write web services. It's fast, thoughtfully architected, and by our account, better to work with than Microsoft's own ASP.NET Web API and Windows Communication Foundation (WCF) frameworks. In this book, we'll show you what it's like to work with ServiceStack in a series of recipes that illustrate how to do things using the framework.
ServiceStack helps you to focus on modeling the messages your service will be exchanging with its clients by specifying data transfer objects (DTO). You might start by creating a DTO class to represent an expected HTTP request and provide an annotation on that class that specifies the expected route. A service will later be created that consumes these requests and returns a response DTO. This focus on the façade that your service presents allows you to easily manage the contract between your service and your consuming clients.
ServiceStack has sought out or created components that help it meet its goals of speed and simplicity. While in most cases, you can bring in your favorite frameworks, it provides several out of the box that are well supported:
Architecturally, ServiceStack favors a common pattern to develop what can be thought of as RESTful web services. REST is wildly popular today, and many consider it the best approach to a Services-oriented architecture.
Perhaps one of the most compelling reasons to use Representational state transfer (REST) is its focus on developing a design based on the concept of a remote resource. You could imagine that an application based on group messaging would require services where users could exchange messages; client applications would communicate by making HTTP connections to remote resources—the remote resource for a group called My Best Friends might be /groups/MyBestFriends. You could query to see what messages were available request by accessing that URL. You could send new messages to that group by sending an HTTP POST to it—the HTTP POST request could contain a JSON object with the sender's name, the text of the message, and other details. You could just as easily remove this group when it's no longer required by sending HTTP DELETE request to the same endpoint. You could specify that you need only JSON data by sending an Accept header set to application/json or specify that you want a web page by asking for application/html. The RESTful approach of designing a remote resource and then interoperating with that resource through simple HTTP calls naturally extends the Web.
ServiceStack's message-based approach often leads to a simpler service interface. SOAP, Microsoft WCF, and even WebAPI encourage a remote procedure call (RPC) style of programming, which encourages the creation of more and more methods—while a message-based approach encourages you to think about your API. We are aware of one project that took an RPC-based approach over two or three years and ended up with over seventy distinct methods being published. A redesign and the careful application of the message pattern reduced this to just two different REST resources. The result was far more manageable—it was also easier to extend, maintain, test, secure, and document.
While a full treatment of developing REST services is outside the scope of this book, the authors will purposefully take a RESTful approach to building services throughout the example. This is not by accident—and is made much easier when working with ServiceStack.
Note: REST in Practice is a great practical book for getting started on the topic of building RESTful services.
There are some requirements that are very common when building web services. For instance, many sites need to validate user input, log requests, or manage the security of the application. ServiceStack comes with some plugins that are very simple to add and that provide advanced functionality through a simple interface. This recipe shows how these features can be added using some of the default plugins available.
There are quite a few plugins that ServiceStack v4.0 comes with, and they are all added the same way; some are standalone, some have dependencies, but they all implement the IPlugin interface. The following are a few examples showing how the required code is added to AppHost in the overridden Configure method:
ValidationFeature enables the use of Fluent Validation to construct easy to read rules. A common usage of these rules is validation of request values before ServiceStack executes the HTTP method of your service:
RegistrationFeature provides new web service endpoints to enable user registration. This feature is commonly used with AuthFeature:
CorsFeature enables your web services to support Cross-Origin Resource Sharing (CORS). This allows JavaScript clients on other domains to use your web services:
The ServiceStack plugins object is just List<IPlugin> that is accessible from your AppHost class.
CorsFeature and ValidationFeature both utilize ServiceStack request filters to enable functionality for each request that is sent to your web services.
AuthFeature and RegistrationFeature create new endpoints to expose functionality as well as enable the use of AuthenticateAttribute to decorate your service classes. You can see this if you look at the metadata page of your application after adding AuthFeature; you'll notice the additional endpoints your application is now hosting.
The following screenshot depicts few of the plugins provided by the ServiceStack framework:
AuthFeature and RegistrationFeature have added four endpoints to enable functionality such as authenticating users and the registration of new ones. The implementation specifics of this depend on how these objects are created.
Plugins are a powerful way to expose reusable functionality across ServiceStack apps with minimal effort. The previous screenshot shows just a few of the plugins that the ServiceStack framework provides. It's easy to add the class implements IPlugin, it can be registered with ServiceStack and will be processed at start-up of the application.