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)?
I always favor OriginalString
as I've ran into multiple issues with AbsoluteUri
. Namely:
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
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
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With