Pass an array of integers to ASP.NET Web API?

前端 未结 17 1730
孤独总比滥情好
孤独总比滥情好 2020-11-22 04:40

I have an ASP.NET Web API (version 4) REST service where I need to pass an array of integers.

Here is my action method:



        
17条回答
  •  情深已故
    2020-11-22 05:06

    My solution was to create an attribute to validate strings, it does a bunch of extra common features, including regex validation that you can use to check for numbers only and then later I convert to integers as needed...

    This is how you use:

    public class MustBeListAndContainAttribute : ValidationAttribute
    {
        private Regex regex = null;
        public bool RemoveDuplicates { get; }
        public string Separator { get; }
        public int MinimumItems { get; }
        public int MaximumItems { get; }
    
        public MustBeListAndContainAttribute(string regexEachItem,
            int minimumItems = 1,
            int maximumItems = 0,
            string separator = ",",
            bool removeDuplicates = false) : base()
        {
            this.MinimumItems = minimumItems;
            this.MaximumItems = maximumItems;
            this.Separator = separator;
            this.RemoveDuplicates = removeDuplicates;
    
            if (!string.IsNullOrEmpty(regexEachItem))
                regex = new Regex(regexEachItem, RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.IgnoreCase);
        }
    
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var listOfdValues = (value as List)?[0];
    
            if (string.IsNullOrWhiteSpace(listOfdValues))
            {
                if (MinimumItems > 0)
                    return new ValidationResult(this.ErrorMessage);
                else
                    return null;
            };
    
            var list = new List();
    
            list.AddRange(listOfdValues.Split(new[] { Separator }, System.StringSplitOptions.RemoveEmptyEntries));
    
            if (RemoveDuplicates) list = list.Distinct().ToList();
    
            var prop = validationContext.ObjectType.GetProperty(validationContext.MemberName);
            prop.SetValue(validationContext.ObjectInstance, list);
            value = list;
    
            if (regex != null)
                if (list.Any(c => string.IsNullOrWhiteSpace(c) || !regex.IsMatch(c)))
                    return new ValidationResult(this.ErrorMessage);
    
            return null;
        }
    }
    

提交回复
热议问题