【问题标题】:How to return GetResponseStream in xml?如何在 xml 中返回 GetResponseStream?
【发布时间】:2014-11-17 10:45:39
【问题描述】:

我正在尝试创建 Web 请求,该请求通过 POST 调用发送 XML,并希望以 XML 形式返回响应。

我对返回 xml 的响应有点困难,因为我很小,我不确定如何在下面的代码中设置它。这是我的尝试:

      // Attempt to receive the WebResponse to the WebRequest.
            using (HttpWebResponse hwresponse = (HttpWebResponse)hwrequest.GetResponse())
            {
                statusCode = (int)hwresponse.StatusCode;
                if (hwresponse != null)
                { // If we have valid WebResponse then read it.
                    using (StreamReader reader = new StreamReader(hwresponse.GetResponseStream()))
                    {
                        // XPathDocument doc = new XPathDocument(reader);
                        string responseString = reader.ReadToEnd();
                        if (statusCode == 201 )
                        {

                          //  var response = new XElement("Status",
                           //    new XElement("status_code", statusCode),
                          //     new XElement("resources_created",
                          ////         new XElement("Link"),
                          //         new XElement("href"),
                          //         new XElement("title")
                          //         ),

                          //         new XElement("warnings")

                           //        );

                            XmlDocument xmlDoc = new XmlDocument();
                            xmlDoc.Load(responseString);
                            XmlNodeList address = xmlDoc.GetElementsByTagName("Status");

                            responseData = xmlDoc.ToString();
                            reader.Close();

                        }
                    }
                }

                hwresponse.Close();

            }

        }
        catch (WebException e)
        {
            if (e.Status == WebExceptionStatus.ProtocolError)
            {
               // XmlDocument xmlDoc = new XmlDocument();
              //  XmlNodeList address = xmlDoc.GetElementsByTagName("Status", statusCode);
               // xmlDoc.Load(xmlDoc);
            }



         //   if (e.Status == WebExceptionStatus.ProtocolError)
         //   {
              //  responseData = "Status Code : {0}" + ((HttpWebResponse)e.Response).StatusCode + "Status Description : {0}" + ((HttpWebResponse)e.Response).StatusDescription;
                // responseData "Status Description : {0}" + ((HttpWebResponse)e.Response).StatusDescription;


           // }
        }

我希望能够以以下 XML 格式返回响应:

<status>
<status_code>201</status_code>
<etag>12345678</etag>
<resources_created>
    <link 
        rel="http://api-info.com" 
        href="http://api-info.com/tag/Some%20Tag" 
        title="Subscriber Tag (Some Tag)" />
</resources_created>
<warnings>
    <warning>Some Warning Message</warning>
</warnings>
</status>

我还想问一下,我的“StatusCode”是否应该设置为 if conditions 或 try&catch。
任何指南都会很有帮助。非常感谢。

【问题讨论】:

    标签: c# asp.net xml web-services


    【解决方案1】:

    您可能无法控制发送给您的内容,但您可以请求带有 Accept 标头的 xml。

    hwrequest.Accept = "application/xml";
    

    但是,您将无法控制结构。

    【讨论】:

    • 感谢您的回复。但我想通过上面提到的格式的 xml 得到响应。我怎样才能做到这一点? ` XmlNodeList address = xmlDoc.GetElementsByTagName("Status");` 这是在正确的行...请指教。非常感谢。
    • 那行可能没问题,但我更熟悉使用 XDocument 而不是 XmlDocument。 responseString 的值是多少?就像我说的,您可以向服务器索要 xml,但您必须处理它要发送给您的内容。 元素也没有关闭。
    • hwrequest.ContentType = "application/xml";将不起作用并使用 .Accept like this answer
    【解决方案2】:

    是的,您应该使用 If/Else 语句处理响应状态(200、201、404 等),而不是依赖 try/catch 来处理您的逻辑。 Try/Catch 用于错误处理,而不是处理常规应用程序流的地方。

    对于 Web 请求,您使用的是过时的 API。除非有特定限制迫使您使用 HttpWebRequest 和 HttpWebResponse,否则您应该使用更新(且更简单)的 API,例如 WebClient 或 HttpClient(仅限 .NET 4.5)。

    http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx http://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.118%29.aspx

    对于响应处理,我建议使用 Linq to XML 而不是旧的 XmlDocument API。

    如果您的响应 XML 在 XML 文档的根部有“status”元素,那么您可以这样做:

    var xmlDoc = XDocument.Load(reader);
    var statusXml = xmlDoc.ToString();
    

    如果“status”元素是另一个根 XML 元素的子元素,那么您可以这样做:

    var xmlDoc = XDocument.Load(reader);
    var statusElement = xmlDoc.Root.Element("status");
    var statusXml = statusElement.ToString();
    

    如果你还想使用旧的HTTP API,你可以摆脱

    string responseString = reader.ReadToEnd();
    

    并像我的示例一样直接在 XDocument.Load 方法中传递 StreamReader。

    如果您升级解决方案以使用例如WebClient 可以使用 DownloadString() 方法,然后将字符串结果加载到 XDocument.Load() 方法中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      相关资源
      最近更新 更多