Search code examples
c#.neturiurl-encoding

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)?


Solution

  • 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