2016-12-14 87 views
2

我已經爲我的對象idAssignmentResult定義了序列化。但是,我該如何將XML的HttpResponseMessage轉換爲它的類?我得到一個錯誤:將HttpResponseMessage轉換爲XML到對象

Value of type 'System.Net.Http.HttpContent' cannot be converted to 'System.Xml.XmlReader'

我會做兩vb.net和c#

vb.net

Dim response As New HttpResponseMessage() 
     Try 
      Using client As New HttpClient() 
       Dim request As New HttpRequestMessage(HttpMethod.Post, "url") 
       request.Content = New StringContent(stringWriter.ToString, Encoding.UTF8, "application/xml") 

       response = client.SendAsync(request).Result 
      End Using 
     Catch ex As Exception 
      lblerror.Text = ex.Message.ToString 
     End Try 
    Dim responseString = response.Content 

    Dim xmls As New XmlSerializer(GetType(idAssignmentResult)) 
    Dim assignmentResult As New idAssignmentResult() 
    xmls.Deserialize(responseString, assignmentResult) /// cannot convert HttpContent to XmlReader 

c#

StringWriter stringWriter = new StringWriter(); 
    XmlSerializer serializer = new XmlSerializer(typeof(personV3R)); 
    personV3R person = new personV3R(); serializer.Serialize(stringWriter, person); 
    HttpResponseMessage response = new HttpResponseMessage(); 
    try 
    { 
     using (HttpClient client = new HttpClient()) 
     { 
      HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "url"); 
      request.Content = new StringContent(stringWriter.ToString, Encoding.UTF8, "application/xml"); 
      response = client.SendAsync(request).Result; 
     } 
    } 
    catch (Exception ex) 
    { 
     lblerror.Text = ex.Message.ToString; 
    } 

    var responseString = response.Content; 

    XmlSerializer xmls = new XmlSerializer(typeof(idAssignmentResult)); 
    idAssignmentResult assignmentResult = new idAssignmentResult(); 
    xmls.Deserialize(responseString, assignmentResult); 

回答

5

您務必做好它作爲

1。

var responseString = await response.Content.ReadAsStringAsync(); 

2.

var assignmentResult = 
      (idAssignmentResult)xmls.Deserialize(new StringReader(responseString)); 
+0

這是它。我不明白在傳遞對象和字符串之間的區別,與你的編號2. –

+0

感謝您的答覆。這幫助我將響應轉換爲對象。將對象轉換回HttpResponseMessage發回的反向是什麼? –