SOAP对象通过HTTP后在C#.NET
题
我想在C#.NET撰写的SOAP消息(包括标题)以发送到使用HTTP后的URL。我想将它发送到URL不是Web服务,它只是接收SOAP消息,最终从中提取信息。如何做到这一点任何想法?
解决方案
首先,你需要创建一个有效的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
}
}
}
其他提示
你的代码上面缺少一个括号,并有一个额外的逗号,我固定在这里:
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")
)
)
)
);
不隶属于 StackOverflow