【问题标题】:Uri Constructor .NET Framework Bug?Uri 构造函数 .NET Framework 错误?
【发布时间】:2011-11-13 12:37:52
【问题描述】:

为什么thirdRelativeUri 失败了?这是一个 .NET 错误吗?好像也没有在 4.0 中修复。

var googleU = new Uri("http://www.google.com");
var secondRelativeUri = new Uri(googleU,"//test.htm"); // doesn't fail
var thirdRelativeUri = new Uri(googleU,"///test.htm"); // fails - Invalid URI: The hostname could not be parsed.

更新:

@dariom 指出这是因为 .NET 中的协议相对 URL 处理是有意义的,但是这对我来说仍然是错误的:

var thirdRelativeUri = new Uri("///test.htm",UriKind.Relative); // works as expected
var newUri = new Uri(googleU,thirdRelativeUri); //Fails, same error even though it's a relative URI

即使第二个 Uri 是Relative,它也会失败

【问题讨论】:

  • 为什么你通过“///test.htm”而不是“//test.htm”??
  • @DavidePiras 因为我很邪恶?我需要提出以下请求:example.com///test.htm 在一个完美的世界中 example.com/test.htm 和 example.com///test.htm 并没有什么不同,但不幸的是,真正的 Web 服务器和框架很疯狂,而且有数千个其中。
  • 我同意@dr.evil。解析应该接受无用的目录/路径分隔符。

标签: c# .net uri


【解决方案1】:

文件 uri 方案 (RFC 1738) file://[host]/path 表明 host 是可选的。 ///test.html 的意思是“由于这通常用于本地文件,因此来自 RFC 1738 的主机通常是空的,导致起始三重 /。(ref)

///test.htm 更改为 file:///test.htm,URI 构造函数将正确解析它。 AbsolutePath 将是 /test.html

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    我认为构造函数将 "//test.htm" 解释为没有方案且主机名为 test.htm 的 URI。您可以通过检查 secondRelativeUri 的值来看到这一点 - 它是 "http://test.htm/"

    您创建的第三个 URI 无效,因为斜杠太多。

    【讨论】:

    • 附带说明,以 // 开头的 URI 称为协议相关 URI。
    • 很好发现,尽管当我明确告诉 .net 它是一个相对 URI 时,它仍然不起作用。更新了问题,添加了新的代码示例。
    【解决方案3】:

    new Uri(googleU,"//test.htm") mean Uri = http://test.html/ /* 有效,反正是某个地方的根 */

    new Uri(googleU,"///test.htm") mean Uri = http:///test.html/ /* 无效,无意义 */

    new Uri("///test.htm",UriKind.Relative); //=> Uri = ///test.htm 同样的错误,不是相对位置

    var r = new Uri("test.htm",UriKind.Relative);

    新的 Uri(googleU, r); // => Uri = http://www.google.com/test.htm

    【讨论】:

    • 这如何回答这个问题?
    【解决方案4】:

    即使在创建相对 URL 时,.net 也会将以两个斜杠开头的字符串视为主机名,例如“//example.org/document”。同样,三个斜杠会造成混淆并引发异常。如果你很确定这些 //test.htm 和 ///test.htm 是路径,那么你可以尝试使用 UriBuilder 类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 2018-11-15
      • 2012-07-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多