Pages

Monday, February 13, 2012

Invoking Web Service dynamically using HttpWebRequest


Yesterday I needed to implement (quickly) a mechanism of dynamic invocation of a web service. I called a Web Service using HttpWebRequest and gathered the response stream. I didn't know the description of the WS (WSDL) in design time. I added some configuration mechanisms to my application tha allow me to change the invoked web service without necesity of recompilation (I will show only the mechanics of WS invocation). How did I invoke this:
Step 1. My Web Service looks like this:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class CustomerWebService : System.Web.Services.WebService
{
    [WebMethod]
    public string Register(long id, string data1)
    {
        return "ID.CUSTOMER";
    }
}
 Step 2. When opened in the Internet Explorer the IIS generates page for my Register method with samples of request. Here is such sample (the olive text is headers description):
POST /WebServices/CustomerWebService.asmx HTTP/1.1
Host: localhost
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/Register"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
  xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <Register xmlns="http://tempuri.org/">
      <id>long</id>
      <data1>string</data1>
    </Register>
  </soap:Body>
</soap:Envelope>
Step 3. Create HttpWebRequest passing the WS url and soap action (similar to method name) and execute the request.
string soap = 
@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
   xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" 
   xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
  <soap:Body>
    <Register xmlns=""http://tempuri.org/"">
      <id>123</id>
      <data1>string</data1>
    </Register>
  </soap:Body>
</soap:Envelope>";

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/WebServices/CustomerWebService.asmx");
req.Headers.Add("SOAPAction", "\"http://tempuri.org/Register\"");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";

using (Stream stm = req.GetRequestStream())
{
     using (StreamWriter stmw = new StreamWriter(stm))
     {
          stmw.Write(soap);
     }
}

WebResponse response = req.GetResponse();

Stream responseStream = response.GetResponseStream();
// TODO: Do whatever you need with the response

No comments:

Post a Comment