none
WCF REST服务POST的时候如果有汉字就报400错误是怎么回事 RRS feed

  • 问题

  • 服务器代码:    
      [ServiceContract]
        public interface IService
        {       
            [WebGet(UriTemplate="/get/{s}",ResponseFormat=WebMessageFormat.Json)]
            User EchoWithGet(string s); 
            [WebInvoke(Method="POST",UriTemplate="Post",ResponseFormat=WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json)]
            User EchoWithPost(User u);
        }
    
     [System.ServiceModel.Activation.AspNetCompatibilityRequirements(RequirementsMode = System.ServiceModel.Activation.AspNetCompatibilityRequirementsMode.Allowed)]
        public class Service1 : IService
        {
            public User EchoWithGet(string s)
            {
                return new User() { Name=s,Sex="男"};
            }
    
            public User EchoWithPost([System.Web.Http.FromBody]User u)
            {
                if (u != null)
                    u.Name += "POST";
                else
                    u = new User() { Name="NULL",Sex="M"};
                return u;
            }
        }
    客户端代码:          
      string json = null;
                WebClient client = new WebClient();
                client.Headers["Content-Type"] = "text/json";
    
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(User));
                using (MemoryStream stream = new MemoryStream())
                {
                    serializer.WriteObject(stream, new User() { Name = "我", Sex = "M" });
                    stream.Flush();
                    json = Encoding.UTF8.GetString(stream.ToArray(), 0, (int)stream.Length);
    
                }
                client.UploadStringCompleted += new UploadStringCompletedEventHandler(client_UploadStringCompleted);
                client.UploadStringAsync(new Uri("http://localhost:4464/post"), "POST",json);
                Console.ReadLine();
    用ajax调用服务有没有汉字都正常,可是用C#的上面的客户端代码调用会出错:远程服务器返回错误: (400) 错误的请求。如果把Name改成英文也就正常。如果用client.UploadData方法一切也是正常的。
    2013年7月20日 13:15

答案