passing complex object to rest wcf

前端 未结 1 659
没有蜡笔的小新
没有蜡笔的小新 2020-12-20 03:23

Passing custom object to REST WCF operation is giving me \"bad request error\". I have tried here with both uri path and query string type methods.Any help is greatly apprec

相关标签:
1条回答
  • 2020-12-20 03:46

    Everything seems to be fine, except that you have to wrap the data in a wrapper, and that is when you get the json data as {"mc":{"name":"Java"}} else you will get only {"name":"Java"} which is not a wrapped request. All these is required because you have set the WebMessageBodyStyle as Wrapped.

    Below is the code.

      [OperationContract]
                [WebInvoke( Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json)]
                string GetBook(myclass mc);
    
         [DataContract]    
            public class myclass
            {
                [DataMember]
                public string name { get; set; }
            }
    
    public string GetBook(myclass mc)
                {
                    return mc.name;
                }
    

    Client:

      public class wrapper
        {
            public myclass mc;
        }
        public class myclass
        {
            public String name;
        }
    
        myclass mc = new myclass();
                    mc.name = "Java";
                    wrapper senddata = new wrapper();
                    senddata.mc = mc;
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    ASCIIEncoding encoder = new ASCIIEncoding();
                    byte[] data = encoder.GetBytes(js.Serialize(senddata));
                    HttpWebRequest req2 = (HttpWebRequest)WebRequest.Create(String.Format(@"http://localhost:1991/Service1.svc/GetBook?"));
                    req2.Method = "POST";
                    req2.ContentType = @"application/json; charset=utf-8";
                    req2.MaximumResponseHeadersLength = 2147483647;
                    req2.ContentLength = data.Length;
                    req2.GetRequestStream().Write(data, 0, data.Length);
                    HttpWebResponse response = (HttpWebResponse)req2.GetResponse();
                    string jsonResponse = string.Empty;
                    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {
                        jsonResponse = sr.ReadToEnd();
                        Response.Write(jsonResponse);
                    }
    

    Hope that helps...

    0 讨论(0)
提交回复
热议问题