posts - 50, comments - 127, trackbacks - 6

My Links

News



View Marcin Celej's profile on LinkedIn

Archives

Post Categories

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

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 |

Feedback

Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

Hi ,I am invoking a web service from another web service , i have doubt regarding step 3 as in which page the code has to be saved like in aspx or asmx .
6/8/2007 2:52 AM | sonu
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest


Hello Dear

i have few confusion regarding your code

1, I am facing same problem , i have tried your given example in aspx code behind , but webservice method is not invoking.

2, you have created a soap string in step 3 , where it is used in given example . i mean where it is used.


regards

Suresh

7/24/2007 11:39 PM | Suresh
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

Thanks for the tip.

I didn't notice the sample is incomplete. I added the code that writes the SOAP to the request stream and gets response.

Thanks once again.
7/25/2007 1:02 AM | Marcin Celej
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

Hello,
I found this page when in search for an example to link a dotnet application to a web server. I tried the code above using Visual Studio 2003 (VB) and constantly get a time-out waiting for the response... I checked the web service using IE and all is well there.
Any idea why there is no answer or any hint where to look?
Thanks!
7/16/2008 6:50 AM | Albert M Thalheim
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

It works on my machine :)
Check if the service is invoked (in logs, by adding logging to the WS, or whatever). If it is not then try to ping the server. If it works then try to generate a proxy using VS. If the proxy will work then I have no idea what is going on. If it does not then it means you have some connection problem (I sometimnes had such problems with port forwarding and WCF web services).
7/16/2008 8:13 AM | Marcin Celej
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

Hello,
I finally found the problem. Nothing to do with the service: the web service timed-out waiting for me to complete the question: I needed to flush and close the GetRequestStream...
Albert M Thalheim
7/21/2008 6:42 AM | Albert M Thalheim
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

Hi, it works perfectly. One question is, if my webservice is returning array of string then how can I create string array from responce xml string? or some complex type which I want to deserialze?
10/3/2008 3:46 AM | mansuri
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

It can be difficult to deserialize it as inside the return stream there is an SOAP envelope and inside the envolpe there is a portion of XML serialized data. You can throw away the SOAP and get the part of the stream with the real information and deserialize it with XMLFormatter (I am not sure if it is the proper class name).
10/5/2008 7:31 AM | Marcin Celej
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

When I do this I am getting "The remote server returned an error: (500) Internal Server Error". Is there any thing that I need to setup on the server?

Thanks in advance
Siva
10/16/2008 7:13 AM | siva
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

If the WS can be invoked from your browser (or the standard proxy approach) it should be invoked with this method also. I believe there is something wrong with the service / server.
10/16/2008 7:23 AM | Marcin Celej
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

I am using almost identical code. Works great in classic exe, or from debugger. But if i call it from a live web page, ResponseStream returns only part of data.

Any ideas ?

Thanks
3/31/2009 12:23 AM | Tex
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

i used above HttpwebRequest code. but i am getting error

The remote server returned an error: (500) Internal Server Error.

Why this error coming?
4/8/2009 1:39 AM | ns
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

Was very helpful. thanks
4/10/2009 8:53 AM | Steady
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

Really nice post :)
Thanks!
5/26/2009 1:35 PM | Cleyton
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

I'm using a very similar technique, but my SOAP response tells me there are multiple pages. When I look at the response...

System.IO.StreamReader str = new System.IO.StreamReader(responseStream);
Console.WriteLine(str.ReadToEnd());

I see that only one page was returned. How do I manipulate this to get the subsequent pages?
5/29/2009 6:14 AM | jqa
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

Hi, I used the code and I can Invoke one Web Service method but if i try to invoke the same method several time I receive this error: "500 internal Error". What is the problem?
7/15/2009 3:03 AM | Pak
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

I have no idea :). You can try to invoke the web serice in the ordinary way several times. If it fails it's all right :). If not, I don't know.
7/15/2009 3:38 AM | Marcin Celej
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

For the 500 error, try this:
public class TrustAllCert
{
public TrustAllCert()
{
}

public bool OnValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
{
return true;
}
}

then in your method:

TrustAllCert trust = new TrustAllCert();

// before your request
ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(trust.OnValidationCallback);
10/19/2009 11:43 AM | DougS
Gravatar

# re: Invoking Web Service dynamically using HttpWebRequest

Thanks for this post, it just works and I think it's fancy
10/21/2009 9:01 PM | Bart
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: