从基本URI和相对路径创建新URI - 斜杠有何不同?

use*_*740 19 .net c# uri trailing-slash

为什么斜杠在使用新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
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 17

为什么斜杠在使用新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路径,如果它不包含任何"/"字符).


Sim*_*wsi 9

我一直在玩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)
Run Code Online (Sandbox Code Playgroud)