DataAnnotations Message Validation

Component: DataAnnotations Message Validator
NuGet Package NServiceBus.DataAnnotations (2.x)
This is a community maintained project
Target NServiceBus Version: 7.x

Uses the NServiceBus.DataAnnotations component to validate various properties of the incoming message and outgoing messages.

Code walk-through

Annotating the message type

In the snippet below, for the type MyMessage, the Content property of the message is marked with a Required attribute defined in the System.ComponentModel.DataAnnotations namespace.

public class MyMessage : IMessage
    public string Content { get; set; }

Configuring the endpoint

The endpoint is then configured to enable the DataAnnotations validator using the snippet below:

configuration.UseDataAnnotationsValidation(outgoing: false);

Running the project

  1. Start the solution.
  2. Two messages of type, MyMessage are automatically sent to the endpoint on start up. The first message has a value for the Content property and the second message has an empty value.
  3. The handler for the message whose Content property has been set will be handled correctly while a validation exception will be thrown for the message whose Content property is empty.

Last modified