views:

415

answers:

2

I am writing a Web service client in C# which takes the URL of the web Service, and a web method name.

I want to check if thew Web method actually receives an int and returns a DataTable, and if this is true, it should call it and return the DataTable.

I have found a couple of posts where this is accomplished compiling dinamically the Proxy class, but for my case this'd be too expensive, because the client is actually a WSS WebPart, and I don't want to do this every time the page is rendered; only when the properties are changed.

A: 

If the Web Service is always the same (i.e. the method is the same as well as what it returns) and uit's just the url that might change, then just add a web reference to the project with the webpart in it, the set the Url of the proxy like so:

using (var serviceProxy = new ServiceProxy())
{
  serviceProxy.Url = somepropertysetbythewebpart;
  // make call to method here
}
Colin
Actually both things can change ... I might be pointing to http://someurl/someservice.asmx in one page, but in another this could be http://someurl/anotherservice.asmx, and the name of the method being called can change as well...
Nicolas Irisarri
+1  A: 

In the end of the day web service description is just an XML file. You can grab it by requesting service.asmx?WSDL:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?WSDL");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();

Once you have service description you can parse it and check method signature. Then, you can invoke the method using HTTP POST:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:1753/Service1.asmx?HelloWorld");
request.Method = "POST";
request.ContentType = "application/soap+xml; charset=utf-8";

byte[] data = Encoding.UTF8.GetBytes(
   @"<?xml version='1.0' encoding='utf-8'?>
   <soap12:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap12='http://www.w3.org/2003/05/soap-envelope'&gt;
     <soap12:Body>
       <HelloWorld xmlns='http://tempuri.org/' />
     </soap12:Body>
   </soap12:Envelope>");

request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
string xml = reader.ReadToEnd();
Pavel Chuchuva
Thks Pavel! I'll get into it And give it a try ... Also I found some info about ServiceDescription object which I think can help me vvalidate the WSDL.
Nicolas Irisarri