2017-06-06 48 views
0

我寫了一個接受字符串和字節參數的WCF寧靜服務。問題是,如果字節爲空,Web服務工作正常,但如果字節參數中有值,則會收到以下錯誤消息:WCF - 如何反序列化一個字節參數

'反序列化System.Byte類型的對象時出現錯誤[]。來自命名空間「'預期的結束元素」文檔「。

這裏是我的代碼

WCF接口

[OperationContract] 
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "IDocument")] 
string IndexDocument(byte[] Document, string DocumentType); 

WCF接口實現

public string IndexDocument(byte[] Document, string DocumentType) 
{ 
} 

客戶端程序

private class Documentt 
     { 
      public byte[] Document { get; set; } 
      public string DocumentType { get; set; } 
     } 



static async Task RunAsync() 
     { 
      byte[] bytes = System.IO.File.ReadAllBytes(openFileDialog.FileName); 

      var parameters = new Documentt() 
      { 
       Document = bytes, 
       DocumentType = "AA" 
      }; 


      using (HttpClient client = new HttpClient()) 
      { 
       var request = new StringContent(JsonConvert.SerializeObject(parameters), Encoding.UTF8, "application/json"); 

       var response = client.PostAsync(new Uri("http://localhost:59005/ServiceCall.svc/IDocument"), request); 
       var result = response.Result; 

      } 
     } 

我在這做錯了什麼?我想利用字節,因爲我想編寫一個跨平臺(用於java,C++,c#等)web服務。

回答

1

這是因爲您使用datacontact作爲您的去污劑,而Json.NET作爲您的滅菌器。請記住它們的行爲與DateTimeByte[]之類的某種對象有所不同。 請使用此方法,以系列化你的要求:

public static string DataJsonSerializer<T>(T obj) 
{ 
    var json = string.Empty; 
    var JsonSerializer = new DataContractJsonSerializer(typeof(T)); 

    using (var mStrm = new MemoryStream()) 
    { 
     JsonSerializer.WriteObject(mStrm, obj); 
     mStrm.Position = 0; 
     using (var sr = new StreamReader(mStrm)) 
      json = sr.ReadToEnd(); 
    } 

    return json; 
} 

你的要求應該是這樣的:

var request = new StringContent(DataJsonSerializer(parameters), Encoding.UTF8, "application/json"); 
+0

這工作完全正常。我不得不將DataContract和DataMember附加到我的Document類以允許此解決方案工作。謝謝.. –

+0

不客氣。 – David