Pergunta

Estou tentando compor uma mensagem SOAP (incluindo cabeçalho) no C# .NET para enviar a um URL usando o HTTP Post. O URL para o qual quero enviá-lo não é um serviço da Web, apenas recebe mensagens de sabão para extrair informações dele. Algumas ideias em como fazer isso?

Foi útil?

Solução

Primeiro você precisa criar um XML válido. Eu uso o LINQ para XML para conseguir isso, como seguir:

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")
                       )
                   )
                );

Então eu o envio usando (EDITAR: adicionado XDocument.ToString() aqui embaixo.)

            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();
            }

Se eu tiver que ler alguma resposta, eu faço (este é o acompanhamento do código acima):

            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
                    }
                }
            }

Outras dicas

Seu código acima estava faltando um parêntese e tinha uma vírgula extra, eu o corrigi aqui:

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") 
            ) 
        ) 
    )
); 
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top