Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uri.AbsoluteUri vs. Uri.OriginalString

I recently became aware of the odd behavior of Uri.ToString() (namely, it unencodes some characters and therefore is primarily suitable for display purposes). I'm trying to decide between AbsoluteUri and OriginalString as my "go-to" for converting a Uri object to a string (e. g. in a razor view).

So far, the only difference I've found between the two is that AbsoluteUri will fail for relative uris (e. g. new Uri("foo", UriKind.Relative).AbsoluteUri). That seems like a point in favor of OriginalString. However, I'm concerned by the word "original", since it suggests that maybe some things will not get properly encoded or escaped.

Can anyone confirm the difference between these two properties (aside from the one difference I found)?

like image 638
ChaseMedallion Avatar asked Mar 08 '16 18:03

ChaseMedallion


2 Answers

I always favor OriginalString as I've ran into multiple issues with AbsoluteUri. Namely:

AbsoluteUri behaves differently in .NET 4.0 vs .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 doesn't support relative URIs

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 does unwanted escaping

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
like image 97
Daniel Liuzzi Avatar answered Nov 13 '22 05:11

Daniel Liuzzi


Normalization is a good reason to use AbsoluteUri over 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
like image 9
Alexei Levenkov Avatar answered Nov 13 '22 06:11

Alexei Levenkov