Andrew Bullock
Andrew Bullock

Reputation: 37378

System.Uri.ToString() unescapes uriencoded querystrings. How to stop it?

If I do:

new Uri("http://www.example.com?name=i%20hate%20asp.net!").ToString()

it doesn't return:

http://www.example.com?name=i%20hate%20asp.net!

it returns:

http://www.example.com?name=i hate asp.net!

Why? How do I make this work correctly?

Upvotes: 3

Views: 433

Answers (2)

eFloh
eFloh

Reputation: 2158

I think this behaviour may be absolutely correct, the ToString()-Method is intended to show human readable results. The Specification for this method says:

(via http://msdn.microsoft.com/de-de/library/system.uri.tostring.aspx)

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

What is your intend with the string representation of the uri? maybe with that information, we can provide the correct solution for youtr problem. I suppose you need to use yourUri.AbsoluteUri instead of yourUri.ToString() in the general case.

Upvotes: 1

Garry Shutler
Garry Shutler

Reputation: 32698

You need to use Uri.AbsoluteUri. ToString() is just a string representation of the underlying data, not a proper URI.

new Uri("http://www.mydomain.com?name=i%20hate%20asp.net!").AbsoluteUri

Upvotes: 4

Related Questions