Book Image

Mastering ServiceStack

By : Andreas Niedermair
Book Image

Mastering ServiceStack

By: Andreas Niedermair

Overview of this book

Table of Contents (13 chapters)

Validating your requests

Supplementary to documentation, when implementing an API there should also be a validation included, as the most important mantra is: don't trust user input.

Whatever validation you will implement in your service, you should start off by implement the IHasResponseStatus interface on your response DTO:

using ServiceStack;

public class HelloResponse : IHasResponseStatus
  public string Result { get; set; }
  public ResponseStatus ResponseStatus { get; set; }

This will guarantee that any exception will get serialized into the ResponseStatus property. Additionally, the following exceptions will adapt the HTTP status code of the request:

  • ArgumentException and descendants returns 400 BadRequest

  • NotImplementedException returns 405 MethodNotAllowed

  • Any other exception returns 500 InternalServerError

You can add custom mappings by adding a translation to the MapExceptionToStatusCode property of your host's config, which also supports inheritance:

using System;
using System...