views:

47

answers:

1

How can one call SOAP webservices from ASP.NET code in runtime and not by adding them as a reference/web-reference in compile time. This is assuming that the application is aware of the list of web services url, the methods and parameters required to call each of the URLs.

Thanks in advance Vijay

A: 

Supposing that you want to invoke the following method:

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}

[WebMethod]
public string HelloWorld(Foo foo)
{
    return "Hello World";
}

You need to construct the correct SOAP envelope:

using (WebClient client = new WebClient())
{
    client.Headers.Add("SOAPAction", "\"http://tempuri.org/HelloWorld\"");
    client.Headers.Add("Content-Type", "text/xml; charset=utf-8");
    var payload = @"<?xml version=""1.0"" encoding=""utf-8""?><soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema""&gt;&lt;soap:Body&gt;&lt;HelloWorld xmlns=""http://tempuri.org/""&gt;&lt;foo&gt;&lt;Id&gt;1&lt;/Id&gt;&lt;Name&gt;Bar&lt;/Name&gt;&lt;/foo&gt;&lt;/HelloWorld&gt;&lt;/soap:Body&gt;&lt;/soap:Envelope&gt;";
    var data = Encoding.UTF8.GetBytes(payload);
    var result = client.UploadData("http://example.com/Service1.asmx", data);
    Console.WriteLine(Encoding.Default.GetString(result));
}

And parse the resulting XML.

Darin Dimitrov
Thanks a lot for the quick response. Let me try this out.RgdsVijay
vijay
Thanks Darin. It worked very well.
vijay