Queue message validation
If you need to validate messages before they're added to Nexus there's two approaches. Either you can let your message class implement IQueueMessageWithValidation
like this:
public class MyMessage : IQueueMessageWithValidation
{
public required int MyProperty { get; set; }
public ValidationResults Validate()
{
return MyProperty < 10 ? ValidationResults.Valid() : ValidationResults.Invalid("Value too high");
}
}
Or you can implement a separate validator class like this:
public class MyMessage : IQueueMessageWithValidation
{
public required int MyProperty { get; set; }
}
public class MyMessageValidator : IQueueMessageValidator<MyMessage>
{
public async Task<ValidationResults> ValidateAsync(MyMessage message)
{
return message.MyProperty < 10 ? ValidationResults.Valid() : ValidationResults.Invalid("Value too high");
}
}
If you have a validator class you don't need to register it, Nexus will find it as long as it's placed in an assembly that's scanned for queue messages. If you need to place the validator in an assembly that's not scanned for messages you can explicitly add the validator by calling AddQueueValidator<MyMessageValidator>()
on the Nexus registration.
The effect of returning ValidationResults.Invalid()
will be that a QueueValidationException
will be thrown and in the case of the API the request will fail with a 400 Bad Request
and with the validation message as the response.
Skipping validation
In some cases you might want to explicitly skip validation, like if the message comes from an external source and it's more important to store the message than validating it. In such cases you can use SkipValidation
on the EnqueueContext
like this:
await enqueuer.EnqueueAsync(message, new EnqueueContext { SkipValidation = true });
API validation
Note that some validation can happen even before your validators are called. Like if you have required
properties on your message class and incoming API requests are missing such values. In that case the deserialization will fail and the API will respond with 400 Bad Request
before your validator is called. If you want to handle these cases yourself you either need to skip the required
part of your properties or prevent the serialization from throwing by implementing your own IQueueMessageSerializer
.