2014-10-06 61 views
0

我正在發送(發佈)Json數據給wcf服務。將Json傳遞給安靜的WCF


public interface IRegisterEmployee 
    { 

     [OperationContract] 
     [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Bare, ResponseFormat=WebMessageFormat.Json, UriTemplate = "AddEmployee")] 
     bool ProcessEmployee(Employee emps); 
    } 

[DataContract] 
    public class Employee 
    { 
     [DataMember] 
     public Emp[] emps { get; set; } 

    } 

DataContract] 
    public class Emp 
    { 
     [DataMember] 
     public string FName { get; set; } 
     [DataMember] 
     public string joinDate {get; set; } 
     [DataMember] 
     public Contact[] contacts {get; set; } 

    } 

DataContract] 
    public class Contact 
    { 
     [DataMember] 
     public string key { get; set; } 
     [DataMember] 
     public string value {get; set; } 

    } 

public class RegisterEmployee : IRegisterEmployee 
    { 
     public bool ProcessEmployee(Employee emps) 
     { 
      //do some processing 
      return true; 

     } 

當我使用提琴手發送輸入數據(JSON),在調試模式下,我看到輸入(emps)包含Emp(即FName和joinDate)的值,但是聯繫人(鍵值)的數據即將到來儘管它存在於輸入中,儘管它是空的。任何想法爲什麼它是空的?如果我用soap/xml測試這個,我可以看到所有的輸入數據,它工作正常。

回答

0

你打電話給你的服務? 我試圖在本地複製的問題,我能得到一些數據調用服務的方式如下:

string sURL = "http://localhost:13104/RegisterEmployee.svc/AddEmployee"; 

     var employee = new Employee 
     { 
      emps = new Emp[1] { 
       new Emp { 
        FName = "MyFName", 
        joinDate = "12/01/2012", 
        contacts = new WcfService1.Contact[1] 
        { 
         new WcfService1.Contact { key = "myKey", value="myVailue" } 
        } 
       } 
      } 
     }; 

     var json = Newtonsoft.Json.JsonConvert.SerializeObject(employee); 

     ASCIIEncoding encoding = new ASCIIEncoding(); 
     byte[] byte1 = encoding.GetBytes (json); 

     WebRequest wrGETURL; 
     wrGETURL = WebRequest.Create(sURL); 
     wrGETURL.Method = "POST"; 
     wrGETURL.ContentType = @"application/json; charset=utf-8"; 
     wrGETURL.ContentLength = byte1.Length; 
     Stream requestStream = wrGETURL.GetRequestStream();    
     requestStream.Write(byte1, 0, byte1.Length); 
     requestStream.Close(); 


     HttpWebResponse webresponse = wrGETURL.GetResponse() as HttpWebResponse; 

     Encoding enc = System.Text.Encoding.GetEncoding("utf-8"); 
     // read response stream from response object 
     StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(), enc); 
     // read string from stream data 
     string strResult = loResponseStream.ReadToEnd(); 
     // close the stream object 
     loResponseStream.Close(); 
     // close the response object 
     webresponse.Close(); 
     // assign the final result to text box 
     Response.Write(strResult); 
+0

就意識到,我是在給小提琴手輸入了格式錯誤。你的例子幫助我識別它。謝謝! – btsdotnet 2014-10-06 16:21:01