2017-06-06 49 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