Description
There are multiple customer-reported issues where the root cause is incorrect usage of Uri.ToString()
:
- [BUG] Getting error for FormRecognizerClient StartRecognizeCustomFormsFromUri for Azure SAS Uri #11564
- [bug] [generator] Uri gets unencoded by calling .ToString() #12069
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())
.