问题
I have some trouble with the UriBuilder and Uri classes in .Net. I want to build my Uri with a UriBuilder, and then use the resulting Uri. However, I cant get it to correctly encode the plus sign in its query string?
Here is a small code example:
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 that the plus sign was encoded to %2b like this http://localhost/?t=a%2bc otherwise I cant use the url.
I could of course build a string instead, but I would prefer to use the strongly typed Uri if possible.
回答1:
Interestingly, this seems to be "fixed" in .NET 4.5.
This is the result of my testing in .NET 4.0: (from the immediate window)
? ub.Uri.ToString()
"http://localhost/?t=a+c"
But in .NET 4.5:
? ub.Uri.ToString()
"http://localhost/?t=a%2bc"
Which is what you are looking for.
Can you upgrade to 4.5? This would fix your problem.
If you cannot upgrade, let me know and I'll attempt to find a work around.
回答2:
I ended up with a custom Uri class wrapping the Uri for now until we have the chance to update to VS2012/.Net4.5. Most Uris in the system Im working on are not created by newing Uris but instead with a Querybuilder method which means it was "easy" to swap that part to return a Uri2 instead of a 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;
}
}
回答3:
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
来源:https://stackoverflow.com/questions/15118269/how-to-avoid-that-uribuilder-creates-uri-with-unencoded-sign-in-its-query-stri