Is there a method to validate URLs in .Net, ASP.Net, or ASP.Net MVC?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can use the Uri.TryCreate to validate an URL:
public bool IsValidUri(string uri)
{
Uri validatedUri;
return Uri.TryCreate(uri, UriKind.RelativeOrAbsolute, out validatedUri);
}
The comments suggest that TryCreate just moves the exception handling one level down. However, I checked the source code and found that this is not the case. There is no try/catch inside TryCreate, it uses a custom parser which should not throw.
Method 2
The answers provided thusfar do not check for a scheme, allowing all kinds of unwanted input, which could make you vulnerable for javascript injection (see the comment of TheCloudlessSky).
An URI is just a unique identification of a object. “C:Test” is a valid URI.
In my project I used the following code:
/// <summary>
/// Validates a URL.
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private bool ValidateUrl(string url)
{
Uri validatedUri;
if (Uri.TryCreate(url, UriKind.Absolute, out Uri validatedUri)) //.NET URI validation.
{
//If true: validatedUri contains a valid Uri. Check for the scheme in addition.
return (validatedUri.Scheme == Uri.UriSchemeHttp || validatedUri.Scheme == Uri.UriSchemeHttps);
}
return false;
}
Define which schemes you will allow and change the code accordingly.
Method 3
You can use Uri.IsWellFormedUriString, no need to create your own function for that:
public static bool IsWellFormedUriString(string uriString, uriKind uriKind);
Where uriKind can be:
UriKind.RelativeOrAbsolute UriKind.Absolute UriKind.Relative
For more info see: http://msdn.microsoft.com/en-us/library/system.uri.iswellformeduristring.aspx
Method 4
In case you need the nice code in VB.Net from Arjan
'Validates a URL.
Function ValidateUrl(url As String) As Boolean
Dim validatedUri As Uri = Nothing
If (Uri.TryCreate(url, UriKind.Absolute, validatedUri)) Then
Return (validatedUri.Scheme = Uri.UriSchemeHttp Or validatedUri.Scheme = Uri.UriSchemeHttps)
End If
Return False
End Function
Method 5
A faster way (probably) than using try/catch functionality would be to use Regex. If you had to validate 1000s of URLs catching the exception multiple times would be slow.
Here’s a link to sample Regex– use Google to find more.
Method 6
static bool IsValidUri(string urlString) {
try {
new Uri(urlString);
return true;
} catch {
return false;
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0