Geeks With Blogs
Marcin Celej blog

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.

Posted on Monday, March 26, 2007 8:33 PM | Back to top


Comments on this post: Invoking Web Service dynamically using HttpWebRequest

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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 .
Left by sonu on Jun 08, 2007 2:52 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...

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

Left by Suresh on Jul 24, 2007 11:39 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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.
Left by Marcin Celej on Jul 25, 2007 1:02 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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!
Left by Albert M Thalheim on Jul 16, 2008 6:50 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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).
Left by Marcin Celej on Jul 16, 2008 8:13 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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
Left by Albert M Thalheim on Jul 21, 2008 6:42 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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?
Left by mansuri on Oct 03, 2008 3:46 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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).
Left by Marcin Celej on Oct 05, 2008 7:31 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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
Left by siva on Oct 16, 2008 7:13 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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.
Left by Marcin Celej on Oct 16, 2008 7:23 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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
Left by Tex on Mar 31, 2009 12:23 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
i used above HttpwebRequest code. but i am getting error

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

Why this error coming?
Left by ns on Apr 08, 2009 1:39 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Was very helpful. thanks
Left by Steady on Apr 10, 2009 8:53 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Really nice post :)
Thanks!
Left by Cleyton on May 26, 2009 1:35 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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?
Left by jqa on May 29, 2009 6:14 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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?
Left by Pak on Jul 15, 2009 3:03 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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.
Left by Marcin Celej on Jul 15, 2009 3:38 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
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);
Left by DougS on Oct 19, 2009 11:43 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Thanks for this post, it just works and I think it's fancy
Left by Bart on Oct 21, 2009 9:01 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Really useful information. I have been ages looking for something like this! Many thanks mate! ;)
Left by Assegurances de cotxe on Feb 24, 2010 12:35 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Make sure you have set validateRequest=false in web.config for pages tag.

[system.web] [pages validateRequest="false"]

PS: [] are just representative, not actual, so that THIS blog post is not blocked.
Left by PKumar on May 10, 2010 9:21 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Just fantastic. I was using a much more complex dynamic service call approach. This is much easier and functional. Just use the c# @ instead of escape character like below:

req.Headers.Add("SOAPAction", @"http://tempuri.org/Register");
req.ContentType = @"text/xml;charset=utf-8";
req.Accept = @"text/xml";
req.Method = "POST";
Left by Net guru from VA on Jun 03, 2010 9:42 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Really nice post.........
Thanks!
Left by Althu Mon on Nov 08, 2010 10:24 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Cool. Clearly .NET.

Now, do it in Java.
Left by Paul A'Barge on Dec 16, 2010 10:14 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Thanks a lot for your code, it make me remember a lot of things that with WCF I started to forgot.
Two point to the other of readers:
1) This code is for soap 1.1 (you can notice with the "<soap", otherwise would be "<soap1.2" or something like that)
2) In the create method, the author forgot to add the name of the webmethod, thats the reason this doesnt work for some of the folks
3) Paul A'Barge, please make constructive comments.
Left by Gabriel Brancolini on Mar 05, 2011 6:04 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
HI..

I have my own web service in my Local machine , When I am add reference in my asp.net application ASMX file is not show and 3 other file are showing in reference folder.
Left by Bhanu Pratap on Dec 06, 2011 10:08 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
You saved my life , I was searching for this solution from almost 2 weeks without hope to find the solution.
Yeah now I can Invoke Web Service dynamically, thank's lot for this great article it was very helpful for me. Thank you a lot !
Keep on coding man , You have a great website ;)
Left by Rafik Soufiane on Aug 06, 2012 12:19 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
This is fantastic:)you saved my day:)
Left by Tina on Sep 03, 2012 11:44 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
You really save my job it is very wonder full post
Left by sumit soni on Sep 05, 2012 11:32 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Thanx sir...
Left by AJ on Oct 08, 2012 10:01 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
can you send me a complete sample, i can't run my code :(
shiva0rahimipour@gmail.com

thanks in advance
Left by sam on Nov 12, 2012 4:29 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Hi
I am trying to use this example in my Windows Phone 8 project.

But some of method does not match. How can I use this example in my Windows Phone example.

Like in this example I have to send Xml data to .asmx service.

Please help me...
Left by Kemal Serkan YILDIRIM on Nov 26, 2012 6:49 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
For 500 error , we could use following code:-

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PartnerBackOfficeUrl);
request.Method = "POST";
request.ContentType = "text/xml";
byte[] data = System.Text.Encoding.UTF8.GetBytes(soap);
request.ContentLength = data.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
HttpStatusCode status = response.StatusCode;
int HTTPcode = Convert.ToInt32(status);
code = HTTPcode;
Left by Abhinav Sharma on Feb 21, 2013 8:24 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Hi , I am facing a problem
In the following code you used
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/WebServices/CustomerWebService.asmx");

If I pass any valid URi inside webrequest.create it returns me HTTP 200 to irrespective of that web service contains that particular web method or not ( webmethod Register in this case).
I tried sending a URi of google it stil returns me HTTP 200.


How to resolve this .. How can i hit my particular webmethod in my webservice.

Left by Abhinav Sharma on Mar 18, 2013 5:44 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Very useful. Thanks
Left by Nick on Feb 19, 2014 3:06 AM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Thank you, this helped me a LOT!
Left by kngbo on Mar 02, 2014 9:31 PM

# re: Invoking Web Service dynamically using HttpWebRequest
Requesting Gravatar...
Great post, works for me.

Can someone help me with parameterizing the request string, not sure if we can do that. I want to send different request with different id and data and test for the result, how the service responds with different sets of data.
Left by vishal on Mar 31, 2014 4:03 AM

Your comment:
 (will show your gravatar)
 


Copyright © Marcin Celej | Powered by: GeeksWithBlogs.net | Join free