Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
919 views
in Technique[技术] by (71.8m points)

c# - HttpUtility.ParseQueryString() always encodes special characters to unicode

When using HttpUtility from System.Web, I find that everytime I call the method .ParseQueryString I am having special characters encode to their unicode equivalent representations. I have tried with many different encoding types, and all seem to produce the same result. An example of my code is here:

string text = "ich m?chte diese Bild für andere freigeben"
var urlBuilder = new UriBuilder(url);
var query = HttpUtility.ParseQueryString(urlBuilder.Query, Encoding.UTF8);
query["text"] = text;    
urlBuilder.Query = query.ToString();
string finalUrl = urlBuilder.ToString();

And the string in finalUrl that I would recieve from this would be:

text=ich+m%u00f6chte+diese+Bild+f%u00fcr+andere+freigeben

I have tried using Encoding.UTF8,Encoding.ASCII and Encoding.Default and they all produce the same result. What can I do to reach my desired format of UrlEncoding:

text=ich%20m%C3%B6chte%20diese%20Bild%20f%C3%BCr%20andere%20freigeben

As always, Thanks in advance for the help/advice!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is in:

urlBuilder.Query = query.ToString();

HttpUtility.ParseQueryString returns a NameValueCollection but is actually an internal class called HttpValueCollection. This class has an override of the ToString() method. It generates an encoded query string but for its URL encoding it uses HttpUtility.UrlEncodeUnicode (tinyurl.com/HttpValue). This results in the %uXXXX values.

If you need a different type of URL encoding you might want to avoid HttpUtility.ParseQueryString or decode the result of ToString() and encode it afterwards:

urlBuilder.Query = Uri.EscapeUriString(HttpUtility.UrlDecode(query.ToString()));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...