UTF-8 String Processing in C # Web Service

I created a simple web service client using the C # wsdl.exe tool. It works fine, except for one. It seems that the UTF-8 strings returned in the response are converted to ASCII. Using SOAPUI, I can see that normal UTF-8 encoded strings are returned by the web service. But when I debug the answer, I got the contents of UTF-8, it seems to have already been converted to ASCII and completely distorted. Where should I see a string containing Japanese characters, I see a list of "?".

  • Is there a way to convert the string back to Unicode so that the original response string is displayed in the debugger?
  • Is there a way to prevent line corruption in a service response?
+3
source share
2 answers

Make sure you actually code the strings according to the @Sam documentation:

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);
    }
}
+1
source

Instead of sending data as a string, try sending data as an array of bytes and converting them to the same encoding on the client side.

0
source

Source: https://habr.com/ru/post/1769098/


All Articles