Book Image

ServiceStack 4 Cookbook

Book Image

ServiceStack 4 Cookbook

Overview of this book

Table of Contents (18 chapters)
ServiceStack 4 Cookbook
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Preface
Index

Intercepting requests and responses using attributes


In many situations, you might have a need to rewrite HTTP requests and even HTTP responses. For instance, you might have certain parts of your API publically accessible and certain parts that require an API key for access. In this case, you wouldn't want to copy and paste this logic all over your service. ServiceStack supports this in the framework in a number of ways—one way that this author is fond of is using custom attributes. You can use these attributes to inject filters, which will be executed prior to executing a service rendering a response. In this recipe, we'll extend the Reidson Industries Messenger to show how to do that.

How to do It…

First, we'll develop a custom request attribute that verifies that an API key is correct. We'll create it as an attribute and have it extend RequestFilterAttribute, as follows:

public class ValidateApiKeyAttribute : RequestFilterAttribute
{
  public override void Execute(
      IRequest req, IResponse...