jason[22]When you deal with command in a CQRS world using for example WebAPI as the transport, well HTTP as transport and WebAPI as host, and you use a toolkit as Jason to handle all the infrastructure what you immediately loose is the full control on the ApiController that handles http requests. Asp.NET WebAPI has an immersive and powerful pipeline where you can plug to add and change behaviors, but loosing control over the controller force you to fallback to the DelegatingHandler WebAPI extension point that is q raw low level, extremely powerful but too much low level for most of the application.

The first thing that comes in to my mind when I think to a command that travels on the wire and that will be handled server side is validation: I must validate the incoming command, period, something coming from the outside cannot be trusted, period #2.

Currently the only option is to validate the incoming command into the command handler itself:

public class MyCommandHandler : ICommandHandler<MyCommand>
{
  public object Execute( MyCommand command )
  {
    //Validate the command...
    //Handle the command here...
    Jason.Defaults.Response.Ok;
  }
}

Is it wrong? No, not really, but we are violating the Single Responsibility Principle, in the end the above class is a command handler not a command validator, isn’t it?

So…

Now if you drop, and register in the container, a class in your project like the following one:

class MyCommandValidator : AbstractValidator<MyCommand> 
{
    public MyCommandValidator()
    {
        this.AddRule(
            property: cmd => cmd.MyProperty,
            error: ctx => "MyProperty is required.",
            rule: ctx => !String.IsNullOrWhiteSpace( ctx.Entity.MyProperty ) );
    }
}

it will be automatically picked up by the infrastructure to validate the incoming MyCommand. By default if the validation fails an HTTP400 (Bad Request) will be returned to the client, with in the message all the details about the validation errors.

Please welcome DataAnnotation support

So, since we have in Asp.Net the support for DataAnnotations why not allow the developer to change the above code to:

class MyCommandValidator : AbstractDataAnnotationValidator<MyCommand> 
{
    public MyCommandValidator()
    {
        this.AddRule(
            property: cmd => cmd.MyProperty,
            error: ctx => "MyProperty is required.",
            rule: ctx => 
            {
                //complex rule that cannot be expressed with an attribute
                return true; //or false to indicate failure.
            } );
    }
}

And have the command defined as:

class MyCommand
{
    [Required]
    public String MyProperty{ get; set; }
}

Inheriting the validator from the AbstractDataAnnotationValidator<T> activates the DataAnnotation support thus we can decorate commands with the data annotations attributes and we can express complex rules using code as in the above sample.

.m