Repository navigation
The model validation attributes MaxLength/MinLength are incompatible with native-aot #58683
Replies: 4 comments
|
Hello, |
|
Thank you for your response. |
|
Addressing validation attribute AOT compatibility This is a real gap — You're right that the Options Validation source generator exists for I built Sannr to address exactly this problem. It's a Roslyn source generator that produces static validation code at compile time — zero reflection, zero For your specific scenario with array length validation: using Sannr;
public partial class MyRequest
{
[Required]
[StringLength(100)]
public string Name { get; set; }
[Required]
[Range(1, 1000)]
public int[] ItemIds { get; set; }
} |
|
Native AOT has limitations with some DataAnnotations attributes because they rely on reflection, which is restricted in trimmed/AOT scenarios. If you specifically need validation for arrays (like Example: public class ArrayLengthAttribute : ValidationAttribute
{
public int Max { get; }
public ArrayLengthAttribute(int max)
{
Max = max;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
if (value is Array arr && arr.Length > Max)
return new ValidationResult($"Maximum allowed items is {Max}");
return ValidationResult.Success;
}
}This avoids some of the trimming/AOT issues while still enabling model validation for arrays. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I am using
System.ComponentModel.DataAnnotations.MaxLengthAttributefor request model validation. However, MaxLengthAttribute is incompatible with native-aot (IL2026). How can I validate my model?I found a validation option that supports source generation, but not for asp.net.
dotnet: 8.0
https://github.com/dotnet/runtime/blob/main/src/libraries/System.ComponentModel.Annotations/src/System/ComponentModel/DataAnnotations/MaxLengthAttribute.cs#L28
https://learn.microsoft.com/en-us/dotnet/core/extensions/options-validation-generator
All reactions