当密码或用户名字段包含特殊字符时,System.Uri 无法解析

发布于 2024-08-24 11:20:12 字数 558 浏览 2 评论 0原文

以下代码抛出 System.UriFormatException:

var uri = new UriBuilder("ftp://user:pass#[email protected]:21/fu/bar.zip");

System.UriFormatException:无效的 URI:需要端口,因为存在冒号 (':'),但无法解析端口。

删除# 符号解决了该问题。

  1. # 符号是密码字段中的有效字符吗?
  2. 有办法逃避这个吗?
  3. 这是 Uri 类解析例程中的已知错误吗?
  4. 假设您无法更改密码,如何解决这个问题? ;-)

谢谢,安德鲁

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.

  1. Is a # symbol a valid character to have in the password field?
  2. Is there a way to escape this?
  3. Is this a known bug in the parsing routine of the Uri class?
  4. How does one get around this - assuming you can't change the password? ;-)

Thanks, Andrew

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

单身情人 2024-08-31 11:20:12

您应该可以使用 %23 代替。

百分号后跟两位十六进制数字是 URL 中字符的转义方式。 23 是 ASCII 表中井号/井号符号的十六进制值。

您不应该解决这个特定问题,而应该通过对整个用户名和密码字段进行编码来解决这个问题。您应该能够使用 System.Web 来执行此操作。 HttpUtility.UrlEncode(参考System.Web程序集):

string username = ...
string password = ...
string url = string.Format("ftp://{0}:{1}@ftp.example.com:21/fu/bar.zip",  HttpUtility.UrlEncode(username),
                                                                           HttpUtility.UrlEncode(password));

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 the System.Web assembly):

string username = ...
string password = ...
string url = string.Format("ftp://{0}:{1}@ftp.example.com:21/fu/bar.zip",  HttpUtility.UrlEncode(username),
                                                                           HttpUtility.UrlEncode(password));
情深已缘浅 2024-08-31 11:20:12

# 需要进行编码,因为它被视为特殊字符。即使这样,也不确定它是否有效。从未尝试过。

The # would need to be encoded, since it's considered a special character. Even then, not sure it would work. Never tried.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文