Uri.AbsoluteUri should be used instead of Uri.ToString()
See original GitHub issueThere are multiple customer-reported issues where the root cause is incorrect usage of Uri.ToString()
:
The problem is Uri.ToString()
un-escapes the URL, so http://foo.com/image%201.jpg
is converted to http://foo.com/image 01.jpg
which is no longer a valid URL. The API Uri.AbsoluteUri
should be used instead.
All instances of Uri.ToString()
in our codebase should be reviewed, and most or all should be convered to Uri.AbsoluteUri
. Uri.ToString()
should only be used to intentionally un-escape a URL, which should be rare. Even if a URL were included in an error message, I think the escaped URL would be preferred.
I recommend adding an analyzer rule to prevent calls to Uri.ToString()
, using Microsoft.CodeAnalysis.BannedApiAnalyzers
.
One complication is relative URIs, where Uri.AbsoluteUri
throws. If we need to get an escaped representation of a relative URI, we can use Uri.EscapeUriString(relativeUri.ToString())
.
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:7 (7 by maintainers)
Top GitHub Comments
Given how tempting ToString() is and how easy it is to get it wrong I suggest to prioritize this work.
I’ll look into merging that PR today.