11

Before .Net 4.5, it seems that System.Uri would unencode encoded slashes, but this has since been fixed. Reference: https://stackoverflow.com/a/20733619/188740

I'm encountering the same problem with colons. System.Uri still unencodes encoded colons. Example:

 var uri = new Uri("http://www.example.com/?foo=http%3A%2F%2Fwww.example.com");
 var s = uri.ToString(); //http://www.example.com/?foo=http:%2F%2Fwww.example.com

Notice how %3A gets switched back to : by System.Uri. Is this a bug? What's the best workaround?

asked May 4, 2017 at 9:24

1 Answer 1

8

How about using Uri.AbsoluteUri instead?

var s = uri.AbsoluteUri; 
// http://www.example.com/?foo=http%3A%2F%2Fwww.example.com

As per the source, uri.ToString() looks like it has logic to unescape certain parts which can be seen here whereas .AbsoluteUri has a much simpler implementation.

Uri.ToString()

As per the MSDN documentation for System.Uri.ToString():

A String instance that contains the unescaped canonical representation of the Uri instance. All characters are unescaped except #, ?, and %.

However as per the example and after trying out a few more strings, it looks like the actual implementation is somwhat like 'Only :, * and spaces are unescaped'

%3A (:) // gets unescaped
%20 ( ) // gets unescaped 
%2A (*) // gets unescaped
%2b, %26, %23, %24, %25 (+, &, #, ,ドル %) // Remain as-is (escaped)

Other Links

answered May 4, 2017 at 9:39
Sign up to request clarification or add additional context in comments.

2 Comments

AbsoluteUri works like a charm. Why do colons get unencoded without AbsoluteUri? Seems like a bug to me.
Yes looks like it. I believe the error is somewhere here which goes ahead and unescapes certain parts. Whereas .AbsoluteUri has a much simpler implementation.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.