StreamContent 从 HttpResponseMessage 到 XML

StreamContent from HttpResponseMessage into XML

我正在从具有此代码的 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") };

    }

我一直在尝试像这样阅读这些信息

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

我得到一个 StreamContent,但我现在想做的是读取此内容并尝试将其反序列化为 Xml 文档以便读取节点。

如何从 HttpContent 的流内容中获取此信息?

string response;

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

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

您可以使用 GetStringAsync 获取字符串而不是 HttpContent 对象。您还错过了 GetAsync 中的 await

注意:代码尚未经过测试