从基本URI和相对路径创建新的URI-斜线会有所不同
本文关键字:URI- 有所不同 创建 URI 路径 相对 | 更新日期: 2023-09-27 17:51:16
为什么在使用新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没有尾部斜杠。
为什么斜线在使用新的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路径任何"/"字符(。
我一直在玩带有重载new Uri(baseUri, relativePath)
的Uri构造函数。也许其他人可能会发现这些结果很有用。以下是我编写的测试应用程序的输出:
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)
我一直在寻找同样的解决方案,并得到了以下解决方案:
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)