【问题标题】:Read XML Response From Page从页面读取 XML 响应
【发布时间】:2016-01-18 20:17:10
【问题描述】:

我正在使用 C# 和 ASP.net 对网页执行 POST。如何读取 XML 响应以了解我的提交是否有错误或成功?

这是我尝试过的,但它只会返回成功/失败消息,不会显示从页面返回的实际 xml。

private void Perform()
{
    this.lblResult.Text = string.Empty;
    Dictionary<string, string> dictFormValues = new Dictionary<string, string>();
    string connectionString = null;
    SqlConnection cnn;
    SqlCommand cmd;
    StringBuilder sql = new StringBuilder();
    SqlDataReader reader;
    string email = string.Empty;
    connectionString = "Data Source=server;Initial Catalog=db;User ID=;Password=";
    sql.Append("select TOP 1 maexst ");
    sql.Append("from redbone.redlight.dbo.maxima ");

    cnn = new SqlConnection(connectionString);
    try
    {
        cnn.Open();
        cmd = new SqlCommand(sql.ToString(), cnn);
        reader = cmd.ExecuteReader();
        while (reader.Read()) { dictFormValues.Add("maexst", reader.GetValue(0).ToString()); }
        reader.Close();
        cmd.Dispose();
        cnn.Close();
    }
    catch (Exception ex) { Response.Write(ex.Message.ToString()); }
    string strIpAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
    string strPageTitle = this.Title;
    string strPageURL = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
    string strError = "";
    bool blnRet = false;
    blnRet = Post(dictFormValues, strPageTitle, strPageURL, ref strError);
    if (blnRet == true)
    {
        this.lblResult.Text = "It was good!";
    }
    else { this.lblResult.Text = strError + ": Error Occured"; }
}

public bool blnRet(Dictionary<string, string> dictFormValues, string strPageTitle, string strPageURL, ref string strMessage)
{
    string strEndpointURL = string.Format("http://testtest12test123.aspx");

    System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
    string strPostData = "";
    foreach (var d in dictFormValues) { strPostData += d.Key + "=" + Server.UrlEncode(d.Value) + "&"; }
    strPostData += "hs_context=";
    System.Net.HttpWebRequest r = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strEndpointURL);
    r.Method = "POST";
    r.Accept = "application/json";
    r.ContentType = "application/x-www-form-urlencoded";
    r.ContentLength = strPostData.Length;
    r.KeepAlive = false;
    using (System.IO.StreamWriter sw = new System.IO.StreamWriter(r.GetRequestStream()))
    {
        try { sw.Write(strPostData); }
        catch (Exception ex)
        {
            strMessage = ex.Message;
            return false;
        }
    }
    return true; 
}

编辑

成功响应

<?xml version="1.0" encoding="utf-8" ?>
<result>
   <success>1</success>
   <postid>12345</postid>
   <errors/>
</result>

失败响应

<?xml version="1.0" encoding="utf-8" ?>
<result>
   <success>0</success>
   <postid/>
   <errors>
      <error>Error Listed Here</error>
      <error>Error 2 Listed Here</error>
      <error>Error 3 Listed Here</error>
   </errors>
</result>

【问题讨论】:

  • 要读取网络响应,您可以调用“r.GetResponseStream()”并使用流阅读器或直接使用 xmldocument 读取它
  • @bdn02 - 你能提供一个这样的例子吗?

标签: c# asp.net xml webforms


【解决方案1】:

试试:

var request = WebRequest.Create("http://some.website/") as HttpWebRequest; 
var response = request.GetResponse();

Stream receiveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

var result =  readStream.ReadToEnd();

这会将页面内容放入result

接下来要做什么取决于实际的响应是什么......从那里你可以使用:

  • XmlDocument.LoadXml
  • XDocument.Parse
  • XElement.Parse

或者也许像HTML Agility Pack 这样的东西会让你解析响应。


使用 XElement 的示例

using System.Xml.Linq;
using System.Linq;
using System.Xml;

var xml = System.Xml.Linq.XElement.Parse(result);
if (xml.Elements("success").FirstOrDefault().Value == "1")
{
   // Process Success
   Console.WriteLine("All Worked!");
}
else
{
   var errors = xml.Elements("errors");
   foreach (var error in errors.Elements("error"))
   {
     // read error messages
     Console.WriteLine(error.Value);
   }
}

(Runnable Fiddle)

解析XElement 可能有一种更简单的方法,但这应该会给你这个想法。

【讨论】:

  • 这让我更近了一步,谢谢!我刚刚编辑了我的帖子以显示响应是如何发送的,如何从变量 result 中解析出响应
  • 我收到以下错误:“System.Collections.Generic.IEnumerable”不包含“元素”的定义,并且没有扩展方法“元素”接受可以找到“System.Collections.Generic.IEnumerable”类型的第一个参数(您是否缺少 using 指令或程序集引用?)
  • 你有using System.Xml.Linq;using System.Linq; 吗?
  • @FunFlyWhiteGuy 我添加了一个可运行的 .net Fiddle。
  • @NikolaiDante - 你能展示一个完整的工作示例吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-31
  • 1970-01-01
  • 2014-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多