You are not doing anything wrong, it's just that WebClient.UploadString does not call Encoding.GetPreamble - it just calls Encoding.GetBytes in the line you passed. For HTTP requests, if you pass strings, you usually specify the encoding in the content header (charset parameter) instead of the one embedded in the file (see the Example below). UploadString does this (it is for the "general case"). As you mentioned, if you want something extra, you can directly load the bytes.
public class StackOverflow_5731102 { [ServiceContract] public class Service { [WebInvoke] public Stream Process(Stream input) { StringBuilder sb = new StringBuilder(); foreach (var header in WebOperationContext.Current.IncomingRequest.Headers.AllKeys) { sb.AppendLine(string.Format("{0}: {1}", header, WebOperationContext.Current.IncomingRequest.Headers[header])); } string contentType = WebOperationContext.Current.IncomingRequest.ContentType; Encoding encoding = Encoding.GetEncoding(contentType.Substring(contentType.IndexOf('=') + 1)); WebOperationContext.Current.OutgoingResponse.ContentType = WebOperationContext.Current.IncomingRequest.ContentType; return new MemoryStream(encoding.GetBytes(sb.ToString())); } } public static void Test() { string baseAddress = "http://" + Environment.MachineName + ":8000/Service"; WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress)); host.Open(); Console.WriteLine("Host opened"); foreach (var encoding in new Encoding[] { new UTF8Encoding(true), new UnicodeEncoding(false, true) }) { Console.WriteLine("Sending encoding = {0}", encoding.WebName); WebClient client = new WebClient(); client.Headers[HttpRequestHeader.ContentType] = "text/plain; charset=" + encoding.WebName; client.Encoding = encoding; string url = baseAddress + "/Process"; string data = "hello"; string result = client.UploadString(url, data); Console.WriteLine(result); Console.WriteLine(string.Join(",", encoding.GetBytes(data).Select(b => b.ToString("X2")))); } Console.Write("Press ENTER to close the host"); Console.ReadLine(); host.Close(); } }
source share