将序列化后的自定义对象传递给WCF

时间:2013-04-26 13:50:07

标签: asp.net wcf rest

我有一个带有以下签名的WCF服务方法:

  public string CTNotification(JSONRecordingCompletedNotification content)
        {

我想创建一个客户端并使用它。我写了下面的代码,但它给出了错误:

using (StreamReader sr = new StreamReader(Server.MapPath("~/json.txt")))
                {
                    string serviceBaseUrl = ConfigurationManager.AppSettings["serviceurl"].ToString() + "CTNotification";
                    string conversationId = ConfigurationManager.AppSettings["conversationId"].ToString();

                    String line = sr.ReadToEnd();
                    string jsonText = line;
                    string body = jsonText;

                JSONRecordingCompletedNotification RecordingCompletedNotification = new JavaScriptSerializer().Deserialize<JSONRecordingCompletedNotification>(body);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceBaseUrl);
                request.Method = "POST";
                request.ContentType = "application/json";                   



                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
                {
                    writer.Write(RecordingCompletedNotification);
                }

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Label1.Text = response.ToString();
            }   

我收到以下错误:

The remote server returned an error: (400) Bad Request.

1 个答案:

答案 0 :(得分:0)

我建议你使用lib进行json序列化和反序列化

  1. json.net

  2. fastjson

  3. 并将内容类型更改为

    request.ContentType = "application/json; charset=utf-8";