Uri(Uri, String)构造函数无法正常工作?

6

这是我的代码的一部分:

Uri branches = new Uri(@"https://127.0.0.1:8443/svn/CXB1/Validation/branches");
Uri testBranch = new Uri(branches, "test");

我希望 testBranches 应该是 https://127.0.0.1:8443/svn/CXB1/Validation/branches/test,但实际上是https://127.0.0.1:8443/svn/CXB1/Validation/test。我不明白为什么 Uri(Uri, string) 构造函数会截取路径的最后一部分。

5
请尝试使用以下代码定义一个Uri变量branches,并将其值设置为"https://127.0.0.1:8443/svn/CXB1/Validation/branches/":`Uri branches = new Uri(@"https://127.0.0.1:8443/svn/CXB1/Validation/branches/");` - I4V
2
Uri 不是路径,它的工作方式与 Path.Combine 不同。https://dev59.com/BHRC5IYBdhLWcg3wOOT1#1527643(请参见评论)。 - Tim Schmelter
3个回答

8
在branches后面添加一个斜杠。
  Uri branches = new Uri(@"https://127.0.0.1:8443/svn/CXB1/Validation/branches/");
  Uri testBranch = new Uri(branches, "test");

在第一个URL末尾添加斜杠也没有效果,因为Uri(string)构造函数会将其删除。而branches将是https://127.0.0.1:8443/svn/CXB1/Validation/branches - Max
抱歉,我在代码的其他部分发现了一个问题。添加斜杠可以解决问题。谢谢。 - Max
这个(即尾随斜杠)有官方文档吗?我找不到任何相关的。 - Rovin Bhandari

3

所看到的行为是正确的,因为如果您想更改文件名,则替换最后一部分是一个好主意。

我建议在第一部分的末尾添加反斜杠。然后就清楚了这是一个目录,否则它可能会被解释为一个文件。

Uri branches = new Uri(@"https://127.0.0.1:8443/svn/CXB1/Validation/branches/");
Uri testBranch = new Uri(branches, "test");
Console.WriteLine(testBranch);

将会得到以下输出:

 https://127.0.0.1:8443/svn/CXB1/Validation/branches/test

2

这是预期的行为。

如果在浏览器中,您正在访问一个完整URI为https://127.0.0.1:8443/svn/CXB1/Validation/branches的页面,并且在该页面上,您单击了一个只有test href的链接,则会跳转到https://127.0.0.1:8443/svn/CXB1/Validation/test。这就是如何使用基本URI组成相对URI。

另一方面,如果第一个URI以/结尾,那么它将按照您的预期工作。


有关此事(即URI应该以这种方式运作)是否有官方文档?我找不到任何相关的资料。 - Rovin Bhandari
@RovinBhandari - 是的,第二个要点似乎已经涵盖了它 - 在添加新文本之前,您需要删除最后一个斜杠右侧的所有字符。 - Damien_The_Unbeliever

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接