最佳URL验证 [英] best URL validation

查看:62
本文介绍了最佳URL验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码即时检查URL验证:

im using code as below to check for the URL validation:

 public static bool CheckURLValid(string strURL)
  {
       Uri uriResult;
       return Uri.TryCreate(strURL, UriKind.Absolute, out uriResult) && uriResult.Scheme == Uri.UriSchemeHttp;
  }

以下结果应全部显示为 true ,但是以某种方式它具有自己的模式来验证url:

The result as below should show all as true, but somehow it has its own pattern to validate the url:

错误:google.com

false: google.com

true : http://www.google.com

错误: true : https://stackoverflow.com/questions/ask

即时通讯使用C#,如何增强此检查网址验证的准确性?

im using c#, how to enhance this checking url validation to be more accurate?

推荐答案

您的CheckURLValid完全返回您告诉的内容.

Your CheckURLValid is returning exactly what you have told it to.

要在所有4个URL上返回True,则存在问题

To return True on all 4 URLs here are the issues

false:google.com

false: google.com

这是一个相对URL,并且您已指定UriKind.Absolute,这意味着它是错误的.

This is a relative url and you have specified UriKind.Absolute which means this is false.

false:这是一个httpS(安全)网址,您的方法说

This is an httpS (Secure) url and your method says

&& uriResult.Scheme == Uri.UriSchemeHttp;

这会将您限制为仅http地址(不安全)

which will limit you to only http addresses (NON secure)

要获得所需的结果,您将需要使用以下方法:

To get the results you are wanting you will need to use the following method:

public static bool CheckURLValid(string strURL)
{
    Uri uriResult;
    return Uri.TryCreate(strURL, UriKind.RelativeOrAbsolute, out uriResult);
}

一种替代方法是只使用

Uri.IsWellFormedUriString(strURL, UriKind.RelativeOrAbsolute);

,而不是重新实现已经准备就绪的功能.如果您想将其包装为自己的CheckUrlValid,我将使用以下代码:

and not re implement functionality that all ready exists. If you wanted to wrap it it your own CheckUrlValid I would use the following:

public static bool CheckURLValid(string strURL)
{
    return Uri.IsWellFormedUriString(strURL, UriKind.RelativeOrAbsolute); ;
}

主要问题是大多数字符串都是有效的相对URL,所以我会避免使用UriKind.RelativeOrAbsolute,因为google.com是无效的URL.大多数Web浏览器都将HTTP://静默添加到字符串中,以使其成为有效的url. HTTP://google.com 是有效的网址.

The main problem is that most strings are valid relative URL's so I would avoid using UriKind.RelativeOrAbsolute as google.com is an invalid url. Most web browsers silently add HTTP:// to the string to make it a valid url. HTTP://google.com is a valid url.

这篇关于最佳URL验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆