C#,有没有比 IsWellFormedUriString 更好的方法来验证 URL 格式? [英] C#, Is there a better way to verify URL formatting than IsWellFormedUriString?

查看:41
本文介绍了C#,有没有比 IsWellFormedUriString 更好的方法来验证 URL 格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更好/更准确/更严格的方法/方式来确定 URL 的格式是否正确?

使用:

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

无法捕获所有内容.如果我输入 htttp://www.google.com 并运行该过滤器,它就会通过.然后我在调用 WebRequest.Create 时得到一个 NotSupportedException.

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.

这个错误的 url 也会让它通过以下代码(这是我能找到的唯一其他过滤器):

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

推荐答案

Uri.IsWellFormedUriString("htttp://www.google.com", UriKind.Absolute) 返回 true 的原因是因为它的形式可能是有效的 Uri.URI 和 URL 不同.

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.

参见:URI 和 URL 有什么区别?

在您的情况下,我会检查 new Uri("htttp://www.google.com").Scheme 是否等于 httphttps.

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

这篇关于C#,有没有比 IsWellFormedUriString 更好的方法来验证 URL 格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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