3

我已经为我的 Object 定义了序列化idAssignmentResult。但是如何将一个是 XML 的 HttpResponseMessage 转换为它的类?我收到一个错误:

“System.Net.Http.HttpContent”类型的值无法转换为“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);
4

1 回答 1

8

你应该这样做

1.

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

2.

var assignmentResult = 
             (idAssignmentResult)xmls.Deserialize(new StringReader(responseString));
于 2016-12-14T20:39:54.287 回答