我使用C#工具wsdl.exe创建了一个简单的Web服务客户端。除了一件事,它工作正常。响应中返回的UTF-8字符串似乎已转换为ASCII。使用SOAPUI,我可以看到Web服务正在返回普通的UTF-8编码的字符串。但是,当我调试响应时,收到的UTF-8内容似乎已经转换为ASCII,并且完全乱码了。在应该看到包含日语字符的字符串的地方,我看到的是“?”列表。
有没有一种方法可以将字符串转换回Unicode,以便在调试器中看到的是原始响应字符串?
有没有一种方法可以防止字符串在服务响应中出现乱码?
最佳答案
确保您实际上根据提供的@Sam文档对字符串进行编码:
using System;
using System.Text;
class UTF8EncodingExample {
public static void Main() {
// Create a UTF-8 encoding.
UTF8Encoding utf8 = new UTF8Encoding();
// A Unicode string with two characters outside an 8-bit code range.
String unicodeString =
"This unicode string contains two characters " +
"with codes outside an 8-bit code range, " +
"Pi (\u03a0) and Sigma (\u03a3).";
Console.WriteLine("Original string:");
Console.WriteLine(unicodeString);
// Encode the string.
Byte[] encodedBytes = utf8.GetBytes(unicodeString);
Console.WriteLine();
Console.WriteLine("Encoded bytes:");
foreach (Byte b in encodedBytes) {
Console.Write("[{0}]", b);
}
Console.WriteLine();
// Decode bytes back to string.
// Notice Pi and Sigma characters are still present.
String decodedString = utf8.GetString(encodedBytes);
Console.WriteLine();
Console.WriteLine("Decoded bytes:");
Console.WriteLine(decodedString);
}
}
关于.net - 在C#Web服务中处理UTF-8字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3913177/