25

为什么在使用new URI(baseUri, relativePath)时斜杠会有所不同?

此构造函数通过组合 baseUri 和 relativeUri 来创建一个 Uri 实例。

而且,如何将相对路径安全/一致地附加到 URI?

var badBase = new Uri("http://amee/noTrailingSlash");
var goodBase = new Uri("http://amee/trailingSlash/");
var f = "relPath";
new Uri(badBase, f)     // BAD  -> http://amee/relPath
new Uri(goodBase, f)    // GOOD -> http://amee/trailingSlash/relPath

即使初始 URI 没有尾部斜杠,所需的输出也是“好”的情况。

4

3 回答 3

20

为什么在使用新的 URI(baseUri,relativePath)时斜杠会有所不同?

嗯,这就是通常在网络上发生的事情。

例如,假设我正在查看http://foo.com/some/file1.html并且有一个指向file2.html- 该链接指向的链接http://foo.com/some/file2.html,对吗?不是http://foo.com/some/file1.html/file2.html

更具体地说,这遵循RFC 3986的第 5.2.3 节。

5.2.3。合并路径

上面的伪代码引用了一个“合并”例程,用于将相对路径引用与基本 URI 的路径合并。这是按如下方式完成的:

  • 如果基础 URI 具有已定义的权限组件和空路径,则返回由 "/" 与引用路径连接的字符串;否则,

  • 返回一个字符串,该字符串由附加到基本 URI 路径的最后一段以外的所有引用的路径组件组成 (即,排除基本 URI 路径中最右边的“/”之后的任何字符,或者排除整个基本 URI 路径,如果它不包含任何“/”字符)。

于 2014-03-20T19:59:48.720 回答
14

我一直在玩 Uri 构造函数的重载new Uri(baseUri, relativePath)。也许其他人可能会发现结果很有用。这是我编写的测试应用程序的输出:

A) Base Address is domain only
==============================

NO trailing slash on base address, NO leading slash on relative path:
http://foo.com   +  relative1/relative2 :
    http://foo.com/relative1/relative2

NO trailing slash on base address, relative path HAS leading slash:
http://foo.com   +  /relative1/relative2 :
    http://foo.com/relative1/relative2

Base address HAS trailing slash, NO leading slash on relative path:
http://foo.com/   +  relative1/relative2 :
    http://foo.com/relative1/relative2

Base address HAS trailing slash, relative path HAS leading slash:
http://foo.com/   +  /relative1/relative2 :
    http://foo.com/relative1/relative2

B) Base Address includes path
=============================

NO trailing slash on base address, NO leading slash on relative path:
http://foo.com/base1/base2   +  relative1/relative2 :
    http://foo.com/base1/relative1/relative2 
    (removed base2 segment)

NO trailing slash on base address, relative path HAS leading slash:
http://foo.com/base1/base2   +  /relative1/relative2 :
    http://foo.com/relative1/relative2
    (removed base1 and base2 segments)

Base address HAS trailing slash, NO leading slash on relative path:
http://foo.com/base1/base2/   +  relative1/relative2 :
    http://foo.com/base1/base2/relative1/relative2
    (has all segments)

Base address HAS trailing slash, relative path HAS leading slash:
http://foo.com/base1/base2/   +  /relative1/relative2 :
    http://foo.com/relative1/relative2
    (removed base1 and base2 segments)
于 2017-03-12T06:06:34.370 回答
1

我一直在寻找相同的解决方案,并得出以下解决方案:

var badBase = new Uri("http://amee/noTrailingSlash");
var goodBase = new Uri("http://amee/trailingSlash/");
var f = "relPath";
string badBaseUrl = Path.Combine(badBase,f);
string goodBaseUrl = Path.Combine(goodBase,f);
new Uri(badBaseUrl);  //----> (http://amee/trailingSlash/relPath)
new Uri(goodBaseUrl); //---> (http://amee/trailingSlash/relPath)
于 2020-07-23T11:42:46.380 回答