2020-10-20 16:20:38 +03:00
|
|
|
using System;
|
|
|
|
using System.ComponentModel.DataAnnotations;
|
|
|
|
|
2020-10-26 17:06:29 +02:00
|
|
|
namespace MalwareMultiScan.Api.Attributes
|
2020-10-20 16:20:38 +03:00
|
|
|
{
|
2020-10-26 21:24:40 +02:00
|
|
|
/// <summary>
|
|
|
|
/// Validate URI to be an absolute http(s) URL.
|
|
|
|
/// </summary>
|
2020-10-29 12:17:09 +02:00
|
|
|
public class IsHttpUrlAttribute : ValidationAttribute
|
2020-10-20 16:20:38 +03:00
|
|
|
{
|
2020-10-30 11:20:08 +02:00
|
|
|
private readonly bool _failOnNull;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Initialize http URL validation attribute.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="failOnNull">True if URL is mandatory, false otherwise.</param>
|
|
|
|
public IsHttpUrlAttribute(bool failOnNull = true)
|
|
|
|
{
|
|
|
|
_failOnNull = failOnNull;
|
|
|
|
}
|
|
|
|
|
2020-10-26 21:24:40 +02:00
|
|
|
/// <inheritdoc />
|
2020-10-20 16:20:38 +03:00
|
|
|
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
|
|
|
|
{
|
2020-10-30 11:20:08 +02:00
|
|
|
if (!_failOnNull && string.IsNullOrEmpty(value.ToString()))
|
|
|
|
return ValidationResult.Success;
|
|
|
|
|
2020-10-29 16:09:56 +02:00
|
|
|
if (!Uri.TryCreate((string) value, UriKind.Absolute, out var uri)
|
|
|
|
|| !uri.IsAbsoluteUri
|
|
|
|
|| uri.Scheme.ToLowerInvariant() != "http"
|
2020-10-29 12:17:09 +02:00
|
|
|
&& uri.Scheme.ToLowerInvariant() != "https")
|
2020-10-26 17:06:29 +02:00
|
|
|
return new ValidationResult("Only absolute http(s) URLs are supported");
|
2020-10-20 17:08:40 +03:00
|
|
|
|
2020-10-20 16:20:38 +03:00
|
|
|
return ValidationResult.Success;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|