如果需要,将方案添加到 URL
要从字符串创建 Uri,您可以这样做:
Uri u = new Uri("example.com");
但问题是,如果字符串(如上面的字符串)不包含协议,您将收到异常:“Invalid URI: The format of the URI might尚未确定。
”
为了避免出现异常,您应该确保字符串包含一个协议,如下所示:
Uri u = new Uri("http://example.com");
但是如果您将 url 作为输入,如果协议丢失,如何添加协议?
我的意思是除了一些 IndexOf/Substring 操作之外?
优雅而快速的东西?
To create a Uri from a string you can do this:
Uri u = new Uri("example.com");
But the problem is if the string (like the one above) doesn't contain the protocol you will get an exception: "Invalid URI: The format of the URI could not be determined.
"
To avoid the exception you should secure the string includes a protocol, like below:
Uri u = new Uri("http://example.com");
But if you take the url as input, how can you add the protocol if it's missing?
I mean apart from some IndexOf/Substring manipulation?
Something elegant and fast?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您还可以使用
UriBuilder< /code>
:
来自 MSDN 的评论:
You could also use
UriBuilder
:Remarks from MSDN:
如果您只想添加方案,而不验证 URL,最快/最简单的方法是使用字符串查找,例如:
更好的方法是使用
Uri
还使用TryCreate
方法:正如 @JanDavidNarkiewicz 在评论中指出的那样,当指定端口没有方案时,验证
Scheme
对于防止无效方案是必要的,例如mydomain.com:80
。If you just want to add the scheme, without validating the URL, the fastest/easiest way is to use string lookups, eg:
A better approach would be to use
Uri
to also validate the URL using theTryCreate
method:As @JanDavidNarkiewicz pointed out in the comments, validating the
Scheme
is necessary to guard against invalid schemes when a port is specified without scheme, e.g.mydomain.com:80
.我的解决方案是针对无协议调用的网址,以确保它们的协议是正则表达式:
My solution was for protocall-less urls to make sure they have protocal was regex :
有趣的是,虽然
Uri
和UriBuilder
在没有方案的情况下完全破坏了任何 url,但WebProxy
却做得对。所以只需调用:
Interestingly, although
Uri
andUriBuilder
completely mangle any url without a scheme,WebProxy
does it right.So just call:
接受的答案结果是 http 而不是 https。我找到了这个答案并以此为基础,
像这样使用它:
The accepted answer results in http and not https. I've found this answer and built up on it
Use it like this:
我们有一些特定的情况,其中有遗留津贴来输入诸如以下内容:
本地主机:8800 或类似的。这意味着我们需要解析它。我们构建了一个更复杂的 ParseUri 方法,它非常松散地分离了指定 URI 的可能性,但也抓住了人们指定非标准方案的时代(以及 IP 长表示法中的主机,因为有时人们会这样做)
就像 UriBuilder 一样,如果未指定,它将默认为 http 方案。如果指定基本身份验证并且密码仅包含数字,则会出现问题。 (随意修复该社区)
We had some specific cases where there was a legacy allowance to input stuff like:
localhost:8800 or similar. Which means we needed to parse that. We built a little more elaborate ParseUri method that separated the possibility to specify a URI very loosely, but also caught the times where people would specify a non-standard scheme (and also the host in IP-long notation, because sometimes people do that)
Just like UriBuilder it will default to the http scheme if none is specified. It will have issues if a basic authentication is specified and the password consists only of numbers. (Feel free to fix that community)