Close this search box.

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 = "")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class CustomerWebService : System.Web.Services.WebService {
  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 : ""

    ? xml version = "1.0" encoding =
          "utf-8"? >
          <soap : Envelope xmlns : xsi =
               "" xmlns : xsd =
                   "" xmlns : soap =
                       ""><soap : Body>
          <Register xmlns = ""><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="""" 
    <Register xmlns="""">

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(
req.Headers.Add("SOAPAction", "\"\"");
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)) {

WebResponse response = req.GetResponse();

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

This type of code I call AGILE PIECE OF CODE – it is good enough to solve some problem although it isn’t fancy.

Print | posted on Monday, March 26, 2007 8:33 PM |

This article is part of the GWB Archives. Original Author:  Marcin Celej

Related Posts