我正在尝试在 C# .NET 中编写 SOAP 消息(包括 header )以使用 HTTP post 发送到 URL。我要将它发送到的 URL 不是 Web 服务,它只是接收 SOAP 消息以最终从中提取信息。关于如何执行此操作的任何想法?
最佳答案
首先您需要创建一个有效的 XML。我使用 Linq to 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
}
}
}
关于c# - C# .NET 中通过 HTTP 发布的 SOAP 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1799005/