5

I have defined the Serialization for my Object idAssignmentResult. But how do I convert an HttpResponseMessage that IS XML, to it's class? I am getting an error:

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

I will do both vb.net and 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);
christopher clark
  • 2,026
  • 5
  • 28
  • 47

1 Answers1

11

You shoud do it as

1.

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

2.

var assignmentResult = 
             (idAssignmentResult)xmls.Deserialize(new StringReader(responseString));
L.B
  • 114,136
  • 19
  • 178
  • 224
  • This was it. I dont understand the difference between passing in the object and the string, vs your number 2. – christopher clark Dec 15 '16 at 14:20
  • thanks for the response. this helped me to convert a response into an object. what is the reverse to convert an object back into a HttpResponseMessage to be sent back? – Denis Wang May 15 '17 at 20:09