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

女生的网名这么多〃 提交于 2019-12-20 21:49:15

问题


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(); 
}

回答1:


The reason Uri.IsWellFormedUriString("htttp://www.google.com", UriKind.Absolute) returns true is because it is in a form that could be a valid Uri. URI and URL are not the same.

See: What's the difference between a URI and a URL?

In your case, I would check that new Uri("htttp://www.google.com").Scheme was equal to http or https.




回答2:


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.




回答3:


@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;
    }
}



回答4:


This Code works fine for me to check a Textbox have valid URL format

if((!string.IsNullOrEmpty(TXBProductionURL.Text)) && (Uri.IsWellFormedUriString(TXBProductionURL.Text, UriKind.Absolute)))
{
     // assign as valid URL                
     isValidProductionURL = true; 

}


来源:https://stackoverflow.com/questions/5629175/c-is-there-a-better-way-to-verify-url-formatting-than-iswellformeduristring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!