I needed to check to see if a URL that the user was entering was a valid Url, does it contain HTTP:// or HTTPS:// I ended up writing a small ValidationAttribute to add to the collection I am now building up, here is the code:
using System;
using System.ComponentModel.DataAnnotations;
using System.Net;
public class IsUriAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var myString = value.ToString();
Uri myUri;
if (Uri.TryCreate(myString, UriKind.Absolute, out myUri) && (myUri.Scheme == Uri.UriSchemeHttp || myUri.Scheme == Uri.UriSchemeHttps))
{
return ValidateUri(myUri);
}
return new ValidationResult("URL is invalid.\nStart with http:// or https:// and end with\na proper image extension");
}
private ValidationResult ValidateUri(Uri myUri)
{
var webRequest = WebRequest.Create(myUri);
try
{
webRequest.GetResponse();
}
catch //If exception thrown then couldn't get response from address
{
return new ValidationResult("URL is invalid and does not exist");
}
return ValidationResult.Success;
}
}