Skip to content

Uri.AbsoluteUri should be used instead of Uri.ToString() #12102

Closed

Description

There 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()).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    ClientThis issue points to a problem in the data-plane of the library.EngSysThis issue is impacting the engineering system.bugThis issue requires a change to an existing behavior in the product in order to be resolved.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions