简体   繁体   English

将StreamContent从HttpResponseMessage转换为XML

[英]StreamContent from HttpResponseMessage into XML

I'm calling an existing get method from a WebApi Controller which has this code (I cannot modify it) 我正在从具有此代码的WebApi控制器调用现有的get方法(我无法对其进行修改)

   [HttpGet]
    public HttpResponseMessage Get()
    {
        XmlDataDocument xmldoc = new XmlDataDocument();
        FileStream fs = new FileStream("d:\\document.xml", FileMode.Open, FileAccess.Read);
        xmldoc.Load(fs);
        string str = xmldoc.DocumentElement.InnerXml;
        return new HttpResponseMessage() { Content = new StringContent(str, Encoding.UTF8, "application/xml") };

    }

I've been trying to read this information like this 我一直在尝试阅读这样的信息

            HttpClient client = new HttpClient();
            HttpResponseMessage response = client.GetAsync("http://localhost/api/info");
            HttpContent content = rm.Content;

I get a StreamContent but what I like to do now is to read this content and try to deserialize it into a Xml Document in order to read the nodes. 我得到了StreamContent,但是我现在想做的是读取此内容,然后尝试将其反序列化为Xml Document以读取节点。

How can I get this information from the Stream Content of the HttpContent? 如何从HttpContent的流内容中获取此信息?

string response;

using(var http = new HttpClient())
{
    response = await http.GetStringAsync("http://localhost/api/info");
}

var xml = new XmlDataDocument();
xml.LoadXml(response);

You can use GetStringAsync to get a string instead of an HttpContent object. 您可以使用GetStringAsync获取字符串,而不是HttpContent对象。 You also missed the await in your GetAsync. 您还错过了GetAsync中的等待状态。

Note: code has not been tested 注意:代码尚未经过测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM