简体   繁体   中英

Decoding capital letters from query string

The QueryString contains foo=Þórþ Örnö Ægirssonð

When I decode it as UTF8 it works for ð, ö, æ but not for the upper case version Ð, Ö, Þ

            byte[] bytes = Encoding.Default.GetBytes(Request.QueryString["foo"]);
            var value = Encoding.UTF8.GetString(bytes);

Here is how this string looks before decoding Ãórþ Ãrnö Ãgirssonð

And here is how it looks after decoding to UTF8 ?órþ ?rnö ?girssonð

Am I missing something? I have tried decoding as UTF7 and any set that works for Icelandic that I found in the Encoding Class on MSDN.

The problem is that you are (probably) using two different encodings: Default for producing the byte array and UTF8 for rebuilding the string. Chances are that on your PC Default differs from UTF8 , and this is messing things up.

You must be careful when using Encoding.Default . Here is how it works (directly quoted from MSDN ):

Different computers can use different encodings as the default, and the default encoding can even change on a single computer. Therefore, data streamed from one computer to another or even retrieved at different times on the same computer might be translated incorrectly. In addition, the encoding returned by the Default property uses best-fit fallback to map unsupported characters to characters supported by the code page. For these two reasons, using the default encoding is generally not recommended. To ensure that encoded bytes are decoded properly, you should use a Unicode encoding, such as UTF8Encoding or UnicodeEncoding, with a preamble. Another option is to use a higher-level protocol to ensure that the same format is used for encoding and decoding.

The UTF8 encoding should be what you are looking for in this case, but you have to apply it coherently:

Byte[] bytes = Encoding.UTF8.GetBytes(Request.QueryString["foo"]);
String value = Encoding.UTF8.GetString(bytes);

Look at this demo , it works fine for me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM