ServiceStack 4 Cookbook - Kyle Hodgson - E-Book

ServiceStack 4 Cookbook E-Book

Kyle Hodgson

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Key Features

    Book Description

    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.

    What you will learn

      Who this book is for

      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:

      EPUB
      MOBI

      Seitenzahl: 441

      Veröffentlichungsjahr: 2015

      Bewertungen
      0,0
      0
      0
      0
      0
      0
      Mehr Informationen
      Mehr Informationen
      Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



      Table of Contents

      ServiceStack 4 Cookbook
      Credits
      About the Authors
      About the Reviewers
      www.PacktPub.com
      Support files, eBooks, discount offers, and more
      Why Subscribe?
      Free Access for Packt account holders
      Preface
      What this book covers
      What you need for this book
      Who this book is for
      Sections
      Getting ready
      How to do it…
      How it works…
      There's more…
      See also
      Conventions
      Reader feedback
      Customer support
      Downloading the example code
      Downloading the color images of this book
      Errata
      Piracy
      Questions
      1. Configuration and Routing
      Introduction
      Why REST?
      Up and running with ServiceStack
      How to do It...
      How it works...
      There's more...
      Routing using data transfer object attributes
      Getting ready
      How to do It...
      How it works...
      There's more...
      Isolating web service routes from a web application
      Getting ready
      How to do It...
      How it works...
      There's more...
      Common ServiceStack plugins
      How to do It...
      How it works...
      Writing a custom audit plugin
      How to do It...
      How it works...
      See also
      Adding Routes via the API
      How to do It...
      How it works…
      There's more...
      Structuring your project to avoid dependency issues
      Getting ready
      How to do It
      Managing dependencies with Funq and Inversion of Control (IoC)
      Getting ready
      How to do It…
      How it works…
      Sharing and accessing configuration and common functionality using Funq IoC
      Getting ready...
      How to do It...
      How it works...
      There's more...
      2. Services and Data Transfer Objects
      Introduction
      Creating a basic create/read/update/delete service
      Getting ready
      How to do it...
      How it works...
      There's more…
      See also
      Splitting HTTP request methods
      Getting ready
      How to do it…
      There's more...
      Hosting services from different assemblies
      Getting ready
      How to do it…
      How it works…
      There's more…
      Utilizing the original HTTP request
      Getting ready
      How to do it…
      How it works…
      There's more…
      See also
      Overriding serialization of request object types
      Getting ready
      How to do it…
      How it works…
      Creating a simple admin service
      Getting ready
      How to do it…
      How it works…
      See also
      Intercepting requests and responses using attributes
      How to do It…
      How it works…
      There's more…
      Making a basic proxy for existing web services
      How to do It…
      How it works…
      Wrapping multiple existing services and exposing them through ServiceStack
      How to do it…
      3. Testing and Logging
      Introduction
      Unit testing ServiceStack applications
      Getting ready
      How to do it…
      How it works…
      There's more…
      Integration testing with the ServiceStack C# client
      Getting ready
      How to do it…
      How it works…
      There's more…
      Functional contract testing ServiceStack services
      Getting ready
      How to do it…
      How it works…
      Testing POST
      Testing PUT
      Testing DELETE
      Accessing the request-and-response object with the JsonServiceClient
      Getting ready
      How to do it…
      How it works…
      There's more…
      Continuous Integration with TeamCity and self-hosted services
      Getting ready
      How to do it…
      How it works…
      There's more…
      Logging with a choice of frameworks
      Getting ready
      How to do it…
      How it works…
      There's more…
      Writing a logger to monitor exceptions via e-mail
      Getting ready
      How to do it…
      How it works…
      There's more…
      4. Object Relational Mapping (OrmLite)
      Introduction
      Modeling your database with types and attributes
      Getting ready
      How to do it…
      How it works…
      PrimaryKey attribute
      AutoIncrement attribute
      References attribute
      There's more…
      Using and accessing OrmLite
      Getting ready
      How to do it…
      How it works…
      See also
      Using OrmLite filters to create audit functionality
      Getting ready
      How to do it…
      How it works…
      There's more…
      CRUD and other common operations
      Getting ready
      How to do it…
      How it works…
      Creating records
      Updating records
      Deleting records
      There's more…
      Utilizing stored procedures using OrmLite
      Getting ready
      How to do it…
      How it works…
      OrmLiteSPStatement
      Writing our own wrapper
      There's more…
      Mapping custom queries to POCOs
      Getting ready
      How to do it…
      How it works…
      Starting with an existing database with OrmLite and T4 templates
      Getting ready
      How to do it…
      How it works…
      There's more…
      Working with Entity Framework and ServiceStack
      Getting ready
      How to do it…
      How it works…
      5. HTML and Form Data
      Introduction
      Getting started with ServiceStack and Razor templates
      Getting ready
      How to do it…
      How it works…
      There's more…
      Using Markdown for website content
      Getting ready
      How to do it…
      How it works…
      Handling file uploads and streaming data from services
      Getting ready
      How to do it…
      How it works…
      There's more…
      Testing file uploads
      Overriding Razor views or templates using attributes
      Getting ready
      How to do it…
      How it works…
      There's more…
      Creating and displaying a login and registration page based on authentication
      Getting ready
      How to do it…
      How it works…
      There's more…
      Submitting a form to a service and handling server-side validation on an HTML client
      Getting ready
      How to do it…
      How it works…
      6. Filters and Validators
      Introduction
      Creating static validation rules using fluent syntax
      How to do it…
      How it works…
      There's more…
      Returning meaningful HTTP error messages
      Getting ready
      How to do it…
      How it works…
      There's more…
      Adding custom headers via the response filter
      Getting ready
      How to do it…
      How it works…
      There's more…
      Restricting file uploads by type using filters
      Getting ready
      How to do it…
      How it works…
      There's more…
      Creating a user-configurable HTTP callback service using a response filter
      Getting ready
      How to do it…
      How it works…
      Applying a rate limit to a web service endpoint using request filter
      Getting ready
      How to do it…
      How it works…
      There's more…
      Restrict user actions by session details using a validator
      Getting ready
      How to do it…
      How it works…
      There's more…
      Common HTTP status codes
      7. Security and Authentication
      Introduction
      Getting started with authentication, sessions, registration, and user repositories
      Getting ready
      How to do it…
      How it works…
      Getting started with Twitter authentication
      Getting ready
      How to do it…
      How it works…
      Getting started with Google authentication

      Getting ready
      How to do it…
      How it works…
      Getting started with Facebook authentication
      Getting ready
      How to do it…
      How it works…
      Using multiple authentication providers and persisting a user's preferred profile image
      Getting ready
      How to do it…
      How it works…
      Handling password resets for credential-based authentication
      Getting ready
      How to do it…
      How it works…
      There's more…
      Accessing Windows identity information from ServiceStack for an intranet application
      Getting ready
      How to do it…
      How it works…
      There's more…
      Validating password complexity with a custom registration validator
      Getting ready
      How to do it…
      How it works…
      Migrating users from another system by overriding ServiceStack's credential-based authentication
      Getting ready
      How to do it…
      How it works…
      There's more…
      Writing your own OpenID authentication provider
      Getting ready
      How to do it…
      How it works…
      8. Working with Redis
      Introduction
      Getting started with ServiceStack.Redis
      Getting ready
      How to do it…
      How it works…
      There's more…
      Using Redis as a cache with the ServiceStack client
      Getting ready
      How to do it…
      How it works…
      There's more…
      Using ServiceStack.Redis for publish/subscribe
      Getting ready
      How to do it…
      How it works…
      Using the ServiceStack.Redis client to access a Redis list
      Getting ready
      How to do it…
      How it works…
      Using Redis hash data structures in ServiceStack
      Getting ready
      How to do it…
      How it works…
      There's More…
      Using Redis Set data structures in ServiceStack
      Getting ready
      How to do it…
      How it works…
      Using typed data structures with ServiceStack and Redis
      Getting ready
      How to do it…
      How it works…
      Scripting Redis with Lua
      Getting ready
      How to do it…
      How it works…
      9. Integrating with Other Technologies
      Introduction
      Integrating with ServiceStack using the C# client and Native Types
      Getting ready
      How to do it…
      How it works…
      Using ServiceStack with WebForms applications
      Getting ready
      How to do it…
      How it works…
      There's more…
      Using ServiceStack with ASP.NET/MVC applications
      Getting ready
      How to do it…
      How it works…
      There's more…
      Broadcasting ServiceStack services with SignalR hubs
      Getting ready
      How to do it…
      How it works…
      There's more…
      Using ServiceStack with MongoDB
      Getting ready
      How to do it…
      How it works…
      There's more…
      Using ServiceStack with Elasticsearch
      Getting ready
      How to do it…
      How it works…
      There's more…
      Working with ServiceStack and AngularJS resources
      Getting ready
      How to do it…
      How it works…
      A. Getting Started
      Creating a ServiceStack solution with Visual Studio and NuGet
      Integrating NUnit
      B. Testing Locally
      Testing external service callbacks locally using Fiddler2 and IIS Express
      Index

      ServiceStack 4 Cookbook

      ServiceStack 4 Cookbook

      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]>)

      Credits

      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

      About the Authors

      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.

      About the Reviewers

      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!"

      www.PacktPub.com

      Support files, eBooks, discount offers, and more

      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.

      Why Subscribe?

      Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

      Free Access for Packt account holders

      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.

      Preface

      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.

      What this book covers

      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.

      What you need for 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:

      Visual Studio 2013 Community Edition or betterMS SQL Server 2008 R2 Express or laterRedis 2.8MongoDB 2.6IIS8 or later

      Who this book is for

      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.

      Sections

      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:

      Getting ready

      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.

      How to do it…

      This section contains the steps required to follow the recipe.

      How it works…

      This section usually consists of a detailed explanation of what happened in the previous section.

      There's more…

      This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

      See also

      This section provides helpful links to other useful information for the recipe.

      Reader feedback

      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.

      Customer support

      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.

      Downloading the example code

      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.

      Downloading the color images of this book

      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.

      Errata

      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

      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.

      Questions

      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.

      Chapter 1. Configuration and Routing

      In this chapter, we'll talk a bit about ServiceStack and we will present the following recipes:

      Up and running with ServiceStackRouting using data-transfer-object attributesIsolating web service routes from a web applicationCommon ServiceStack pluginsWriting a Custom Audit pluginAdding Routes via the APIStructuring your project to avoid dependency issuesManaging dependencies with Funq and Inversion of Control (IoC)Sharing and accessing configurations and common functionalities using Funq IoC

      Introduction

      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:

      ServiceStack's JsonSerializer is much faster than both Microsoft Base Class Library and DataContractSerializer and faster than other competing open source serializersServiceStack includes a slightly modified version of the open source Funq DI container known for its performance and simplicityServiceStack includes ServiceStack.OrmLite, which is much faster than Microsoft's own Entity Framework and most other ORMs

      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.

      Why REST?

      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

      Note: REST in Practice is a great practical book for getting started on the topic of building RESTful services.

      Common ServiceStack plugins

      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.

      How to do It...

      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:

      Plugins.Add(new ValidationFeature());

      RegistrationFeature provides new web service endpoints to enable user registration. This feature is commonly used with AuthFeature:

      Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider() })); Plugins.Add(new RegistrationFeature());

      CorsFeature enables your web services to support Cross-Origin Resource Sharing (CORS). This allows JavaScript clients on other domains to use your web services:

      Plugins.Add(new CorsFeature());

      How it works...

      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.