using IdentityServer4.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BZPT.DTO { [AttributeUsage(AttributeTargets.Property)] public class MaxByteLengthAttribute : ValidationAttribute { private readonly Encoding _encoding = Encoding.UTF8; private readonly int _maxBytes; public MaxByteLengthAttribute(int maxBytes) { _maxBytes = maxBytes; } protected override ValidationResult IsValid(object value, ValidationContext context) { if (value is string str && _encoding.GetByteCount(str) > _maxBytes) { return new ValidationResult(ErrorMessage ?? $"字节长度超过 {_maxBytes}"); } return ValidationResult.Success; } } }