当密码或用户名字段包含特殊字符时,System.Uri 无法解析
以下代码抛出 System.UriFormatException:
var uri = new UriBuilder("ftp://user:pass#[email protected]:21/fu/bar.zip");
System.UriFormatException:无效的 URI:需要端口,因为存在冒号 (':'),但无法解析端口。
删除# 符号解决了该问题。
- # 符号是密码字段中的有效字符吗?
- 有办法逃避这个吗?
- 这是 Uri 类解析例程中的已知错误吗?
- 假设您无法更改密码,如何解决这个问题? ;-)
谢谢,安德鲁
The following code throws System.UriFormatException:
var uri = new UriBuilder("ftp://user:pass#[email protected]:21/fu/bar.zip");
System.UriFormatException: Invalid URI: A port was expected because of there is a colon (':') present but the port could not be parsed.
Removing the # symbol from the password field solves the issue.
- Is a # symbol a valid character to have in the password field?
- Is there a way to escape this?
- Is this a known bug in the parsing routine of the Uri class?
- How does one get around this - assuming you can't change the password? ;-)
Thanks, Andrew
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该可以使用 %23 代替。
百分号后跟两位十六进制数字是 URL 中字符的转义方式。 23 是 ASCII 表中井号/井号符号的十六进制值。
您不应该解决这个特定问题,而应该通过对整个用户名和密码字段进行编码来解决这个问题。您应该能够使用
System.Web 来执行此操作。 HttpUtility.UrlEncode
(参考System.Web
程序集):You should be able to use %23 instead.
The percent symbol followed by a two digit hex number is how characters are escaped in URLs. 23 is the hexadecimal value for the hash/pound symbol in the ASCII table.
Rather than solving this particular problem, you should solve this problem generally by encoding the whole username and password fields. You should be able to do this with
System.Web.HttpUtility.UrlEncode
(reference theSystem.Web
assembly):# 需要进行编码,因为它被视为特殊字符。即使这样,也不确定它是否有效。从未尝试过。
The # would need to be encoded, since it's considered a special character. Even then, not sure it would work. Never tried.