How to avoid UriBuilder creating a Uri with an unregistered + sign in the query string?

I have some problems with the UriBuilder and Uri tutorials in .NET. I want to build Uri with UriBuilder and then use the resulting Uri. However, I canโ€™t get him to correctly encode the plus sign in his query string?

Here is an example of a little code:

var ub = new UriBuilder(); ub.Query = "t=a%2bc"; Console.WriteLine(ub.Uri.ToString()); 

This example gives me http://localhost/?t=a+c , but I would expect the plus sign to be encoded in% 2b, like this, http://localhost/?t=a%2bc , otherwise I will not I can use url.

I could, of course, create a string instead, but I would rather use a strongly typed Uri, if possible.

+1
urlencode
Feb 27 '13 at 17:21
source share
3 answers

Interestingly, this is apparently โ€œfixedโ€ in .NET 4.5.

This is the result of my testing in .NET 4.0 : (from a direct window)

 ? ub.Uri.ToString() "http://localhost/?t=a+c" 

But in .NET 4.5 :

 ? ub.Uri.ToString() "http://localhost/?t=a%2bc" 

This is what you are looking for.

Can you upgrade to 4.5? This will fix your problem.

If you cannot update, let me know and I will try to find a job.

+2
Feb 27 '13 at 19:16
source share

As a result, I got a custom Uri class, which now exchanges Uri until we have the opportunity to upgrade to VS2012 / .Net4.5. Most Uris in the Im system working on them are not created by adding Uris, but instead using the Querybuilder method, which means it was โ€œeasyโ€ to replace this part to return Uri2 instead of Uri.

 public class Uri2 : Uri { public Uri2(Uri uri) : base(uri.ToString()) { } public override string ToString() { var s = base.ToString(); s = s.Replace("+", "%2b"); return s; } } 
+1
Feb 28 '13 at 9:55
source share

Use AbsoluteUri instead of ToString ():

 var ub = new UriBuilder(); ub.Query = "t=a%2bc"; Console.WriteLine(ub.Uri.AbsoluteUri); 

this gives the correct result:

 http://localhost/?t=a%2bc 
+1
Jul 09 '13 at 20:19
source share



All Articles