Skip to content

Instantly share code, notes, and snippets.

@ramonsmits
Created June 16, 2022 15:59
Show Gist options
  • Save ramonsmits/b74a26e4cb85f093750d8f2b003bc0bb to your computer and use it in GitHub Desktop.
Save ramonsmits/b74a26e4cb85f093750d8f2b003bc0bb to your computer and use it in GitHub Desktop.
NServiceBus 7 - Behavior that validates if the serialized body does not exceed a configurable limit
//
// Usage:
//
// var endpointConfiguration = new EndpointConfiguration("MyEndpoint")
// ...
// endpointConfiguration.Pipeline.Register(new CheckSizeBehavior(CheckSizeBehavior.StandardTierMaxSize), nameof(CheckSizeBehavior));
//
using NServiceBus.Pipeline;
class CheckSizeBehavior : IBehavior<IOutgoingPhysicalMessageContext, IOutgoingPhysicalMessageContext>
{
public const int StandardTierMaxSize = 256 * 1024; // Kilobyte not, Kebibyte
public const int PremiumTierMaxSize = 100 * 1024 * 1024; //Megabyte, not Mebibyte
readonly int MaxBodySize;
public CheckSizeBehavior(int maxBodySize)
{
MaxBodySize = maxBodySize;
}
public Task Invoke(IOutgoingPhysicalMessageContext context, Func<IOutgoingPhysicalMessageContext, Task> next)
{
if (context.Body.Length > MaxBodySize)
{
throw new InvalidOperationException($"Body length exceeds configured maxium body size ({MaxBodySize}bytes).");
}
return next(context);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment