Created
June 16, 2022 15:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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