8

How do I stop the System.Uri class from unencoding an encoded URL passed into its constructor? Consider the following code:-

Uri uri = new Uri("http://foo.bar/foo%2FBar");
Console.WriteLine(uri.AbsoluteUri);
uri = new Uri("http://foo.bar/foo%2FBar", false);
Console.WriteLine(uri.AbsoluteUri);
uri = new Uri("http://foo.bar/foo%2FBar", true);
Console.WriteLine(uri.AbsoluteUri);

In each case the output is "http://foo.bar/foo/bar". How can I ensure that after instantiating a Uri instance, Uri.AbsoluteUri will return "http://foo.bar/foo%2FBar"?

Cleggy
  • 715
  • 9
  • 24

1 Answers1

4

The Uri class isn't used to generate an escaped URI, although you can use uri.OriginalString to retrieve the string used for initialization. You should probably be using UrlEncode if you need to reencode a URI safely.

Also, as per http://msdn.microsoft.com/en-us/library/9zh9wcb3.aspx the dontEscape parameter in the Uri initializer has been deprecated and will always be false.

UPDATE:

Seems someone found a way (hack) to do this - GETting a URL with an url-encoded slash

Community
  • 1
  • 1
PinnyM
  • 35,165
  • 3
  • 73
  • 81
  • I am already using UrlEncode. My problem is actually when attempting to construct a HttpWebRequest instance to make a REST call where the URL may have escaped characters in it (including a slash as demonstrated above). I was using the WebRequest.Create(UrlString) overload to create the request, and found that the URL being passed to the server was unencoding the encoded slash, causing a server-side error. Further testing revealed this was probably a problem with the Uri class, hence my question. – Cleggy Apr 03 '12 at 10:03
  • Thanks for the link there, PinnyM. Due to the "Terrible hack" nature of it, I'm wondering whether I should go that route, or take another tack entirely to solve my problem. Currently I'm attempting to call a REST service, but I have the flexibility to change this to a SOAP one instead, which should also alleviate this issue. Nevertheless, you've solved this particular problem, so I'm going to mark this as the correct answer. – Cleggy Apr 03 '12 at 20:15