Uri.AbsoluteUri 对比 Uri.OriginalString

Uri.AbsoluteUri vs. Uri.OriginalString

我最近开始意识到 Uri.ToString() 的奇怪行为(即,它不对某些字符进行编码,因此主要适用于显示目的)。我试图在 AbsoluteUriOriginalString 之间做出决定,因为我的 "go-to" 用于将 Uri 对象转换为字符串(例如,在剃须刀视图中)。

到目前为止,我发现两者之间的唯一区别是 AbsoluteUri 对于相对 uris(例如 new Uri("foo", UriKind.Relative).AbsoluteUri)会失败。这似乎是支持 OriginalString 的观点。但是,我对 "original" 这个词很担心,因为它暗示可能有些东西无法正确编码或转义。

谁能确认这两个属性之间的区别(除了我发现的一个区别)?

标准化是使用 AbsoluteUri 而不是 OriginalString 的一个很好的理由:

new Uri("http://foo.bar/var/../gar").AbsoluteUri // http://foo.bar/gar
new Uri("http://foo.bar/var/../gar").OriginalString // http://foo.bar/var/../gar

我总是喜欢 OriginalString,因为我 运行 遇到过 AbsoluteUri 的多个问题。即:

AbsoluteUri 在 .NET 4.0 和 .NET 4.5 中的行为不同 (see)

.NET Framework 4.0

var uri = new Uri("http://www.example.com/test%2F1");

Console.WriteLine(uri.OriginalString);
// http://www.example.com/test%2F1

Console.WriteLine(uri.AbsoluteUri);
// http://www.example.com/test/1  <--  WRONG

.NET Framework 4.5

var uri = new Uri("http://www.example.com/test%2F1");

Console.WriteLine(uri.OriginalString);
// http://www.example.com/test%2F1

Console.WriteLine(uri.AbsoluteUri);
// http://www.example.com/test%2F1

AbsoluteUri 不支持相对 URI

var uri = new Uri("/test.aspx?v=hello world", UriKind.Relative);

Console.WriteLine(uri.OriginalString);
// /test.aspx?v=hello world

Console.WriteLine(uri.AbsoluteUri);
// InvalidOperationException: This operation is not supported for a relative URI.

AbsoluteUri 进行不需要的转义

var uri = new Uri("http://www.example.com/test.aspx?v=hello world");

Console.WriteLine(uri.OriginalString);
// http://www.example.com/test.aspx?v=hello world

Console.WriteLine(uri.AbsoluteUri);
// http://www.example.com/test.aspx?v=hello%20world  <--  WRONG

为了将 Uri 对象转换为字符串,我使用了

Location.ToString().StripQuotes();

请注意,ToString 生成了 url 用双引号 " 包裹的字符串,我不得不使用 Flurl/src/Flurl/Util/CommonExtensions.cs

中的 StripQuotes 删除它们

另请参见 MSDN example,它说明了从 OriginalString 返回的值(returns 传递给构造函数的字符串)与调用 ToString 返回的值之间的区别,returns 字符串的规范形式。