Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, Is there a better way to verify URL formatting than IsWellFormedUriString?

Is there a better/more accurate/stricter method/way to find out if a URL is properly formatted?

Using:

bool IsGoodUrl = Uri.IsWellFormedUriString(url, UriKind.Absolute);

Doesn't catch everything. If I type htttp://www.google.com and run that filter, it passes. Then I get a NotSupportedExceptionlater when calling WebRequest.Create.

This bad url will also make it past the following code (which is the only other filter I could find):

Uri nUrl = null;
if (Uri.TryCreate(url, UriKind.Absolute, out nUrl))
{
    url = nUrl.ToString(); 
}
like image 794
PiZzL3 Avatar asked Apr 12 '11 00:04

PiZzL3


2 Answers

@Greg's solution is correct. However you can steel using URI and validate all protocols (scheme) that you want as valid.

public static bool Url(string p_strValue)
{
    if (Uri.IsWellFormedUriString(p_strValue, UriKind.RelativeOrAbsolute))
    {
        Uri l_strUri = new Uri(p_strValue);
        return (l_strUri.Scheme == Uri.UriSchemeHttp || l_strUri.Scheme == Uri.UriSchemeHttps);
    }
    else
    {
        return false;
    }
}
like image 152
equiman Avatar answered Sep 22 '22 19:09

equiman


Technically, htttp://www.google.com is a properly formatted URL, according the URL specification. The NotSupportedException was thrown because htttp isn't a registered scheme. If it was a poorly-formatted URL, you would have gotten a UriFormatException. If you just care about HTTP(S) URLs, then just check the scheme as well.

like image 25
Mark Cidade Avatar answered Sep 20 '22 19:09

Mark Cidade