2009-11-25 55 views
12

我想在C#.NET中使用HTTP發佈來發送到URL的SOAP消息(包括頭文件)。我想要發送給它的URL不是一個Web服務,它只是接收SOAP消息以最終從中提取信息。任何想法如何做到這一點?C#.NET中通過HTTP發佈的SOAP對象

回答

15

首先您需要創建一個有效的XML。我使用LINQ到XML來實現這一點,就像如下:

XNamespace soapenv = "http://schemas.xmlsoap.org/soap/envelope/"; 
var document = new XDocument(
       new XDeclaration("1.0", "utf-8", String.Empty), 
       new XElement(soapenv + "Envelope", 
        new XAttribute(XNamespace.Xmlns + "soapenv", soapenv), 
        new XElement(soapenv + "Header", 
         new XElement(soapenv + "AnyOptionalHeader", 
          new XAttribute("AnyOptionalAttribute", "false"), 
         ) 
        ), 
        new XElement(soapenv + "Body", 
         new XElement(soapenv + "MyMethodName", 
          new XAttribute("AnyAttributeOrElement", "Whatever") 
         ) 
        ) 
       ); 

然後,我用它發送(編輯:添加XDocument.ToString()到這裏)

  var req = WebRequest.Create(uri); 
      req.Timeout = 300000; //timeout 
      req.Method = "POST"; 
      req.ContentType = "text/xml;charset=UTF-8"; 

      using (var writer = new StreamWriter(req.GetRequestStream())) 
      { 
       writer.WriteLine(document.ToString()); 
       writer.Close(); 
      } 

如果我要讀一些響應,我這樣做(這是上面的代碼的後續):

  using (var rsp = req.GetResponse()) 
      { 
       req.GetRequestStream().Close(); 
       if (rsp != null) 
       { 
        using (var answerReader = 
           new StreamReader(rsp.GetResponseStream())) 
        { 
         var readString = answerReader.ReadToEnd(); 
         //do whatever you want with it 
        } 
       } 
      } 
+0

你說得對,有一個更簡單的方法來將'XDocument'轉換爲字符串。這是'ToString()'方法。有一個重載,可讓您指定是否要縮進和格式化XML(默認爲格式化)。 – 2009-11-25 21:12:44

+0

謝謝你,改變了我的代碼和上面的例子。 – 2009-11-26 07:58:26

+0

這是什麼「使用」? – baash05 2011-04-19 23:01:30

0

上面的代碼中缺少一個括號,並有一個額外的逗號,我固定在這裏:

XNamespace soapenv = "http://schemas.xmlsoap.org/soap/envelope/"; 
var document = new XDocument( 
    new XDeclaration("1.0", "utf-8", String.Empty), 
    new XElement(soapenv + "Envelope", 
     new XAttribute(XNamespace.Xmlns + "soapenv", soapenv), 
     new XElement(soapenv + "Header", 
      new XElement(soapenv + "AnyOptionalHeader", 
       new XAttribute("AnyOptionalAttribute", "false") 
      ) 
     ), 
     new XElement(soapenv + "Body", 
      new XElement(soapenv + "MyMethodName", 
       new XAttribute("AnyAttributeOrElement", "Whatever") 
      ) 
     ) 
    ) 
);