using System; using System.ComponentModel.DataAnnotations; namespace MalwareMultiScan.Api.Attributes { /// /// Validate URI to be an absolute http(s) URL. /// public class IsHttpUrlAttribute : ValidationAttribute { private readonly bool _failOnNull; /// /// Initialize http URL validation attribute. /// /// True if URL is mandatory, false otherwise. public IsHttpUrlAttribute(bool failOnNull = true) { _failOnNull = failOnNull; } /// protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (!_failOnNull && string.IsNullOrEmpty(value.ToString())) return ValidationResult.Success; if (!Uri.TryCreate((string) value, UriKind.Absolute, out var uri) || !uri.IsAbsoluteUri || uri.Scheme.ToLowerInvariant() != "http" && uri.Scheme.ToLowerInvariant() != "https") return new ValidationResult("Only absolute http(s) URLs are supported"); return ValidationResult.Success; } } }