HttpWebResponse and Int

本文关键字:Int and HttpWebResponse | 更新日期: 2023-09-27 18:20:41

我正在与REST服务集成,到目前为止一切都很好。打一点栏。我正在通过HttpWebRequest访问该服务。我成功地接收到了响应,但在通过StreamReader运行HttpWebResponse GetResponseStream时,我得到了一个

<int xmlns="http://schemas.microsoft.com/2003/10/Serialization/">427</int>.

有点纠结于如何将其转换回c#int.

有什么建议吗?

谢谢。

HttpWebResponse and Int

您可以结合XDocument来查看int.Parseint.TryParse方法,您可以使用XDocument将响应XML加载到:

var request = WebRequest.Create(...);
...
using (var response = request.GetResponse())
using (var stream = response.GetStream())
{
    var doc = XDocument.Load(stream);
    if (int.TryParse(doc.Root.Value, out value))
    {
        // the parsing was successful => you could do something with
        // the integer value you have just read from the body of the response
        // assuming the server returned the XML you have shown in your question,
        // value should equal 427 here.
    }
}

或者更简单的是,XDocument的Load方法理解HTTP,所以你甚至可以这样做:

var doc = XDocument.Load("http://foo/bar");
if (int.TryParse(doc.Root.Value, out value))
{
    // the parsing was successful => you could do something with
    // the integer value you have just read from the body of the response
    // assuming the server returned the XML you have shown in your question,
    // value should equal 427 here.
}

这样,您甚至不需要使用任何HTTP请求/响应。一切都将由BCL为您处理,这有点棒。

如果您只是想将字符串"427"转换为int,请使用Int32.Parse方法。

var str = "427";
var number = Int32.Parse(str);  // value == 427