问题描述
在使用HttpUtility从System.Web程序,我发现,每次我调用该方法.ParseQueryString我有特殊字符编码为它们的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();
而在 finalUrl
,我将字符串从这个收到将是:
And the string in finalUrl
that I would recieve from this would be:
文本= ICH + M%u00f6chte + diese +画报+ F%u00fcr + ANDERE + freigeben
我已经尝试使用 Encoding.UTF8
, Encoding.ASCII>
和 Encoding.Default
,他们都产生相同的结果。我能做些什么来达到我想要的URL编码的格式为:
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:
文本= ICH%20米%C3%B6chte%20diese%20Bild%20F% C3%BCR%20andere%20freigeben
和往常一样,在此先感谢您的帮助/咨询!
As always, Thanks in advance for the help/advice!
推荐答案
的问题是:
urlBuilder.Query = query.ToString();
HttpUtility.ParseQueryString
返回的NameValueCollection
但实际上是被称为内部类 HttpValueCollection
。此类具有的ToString()
方法的重写。它产生一个编码的查询字符串,但它的URL编码,它使用 HttpUtility.UrlEncodeUnicode
(tinyurl.com/HttpValue)。这导致了%uXXXX值。
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.
如果你需要一个不同类型的URL编码的,你可能要避免 HttpUtility.ParseQueryString
或的ToString()事后对其进行编码:
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()));
这篇关于HttpUtility.ParseQueryString()总是特殊字符编码为Unicode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!