How to call a SOAP web service in .NET 4.0 C# without using the WSDL or proxy classes

If you want to call a .NET 4.0 C# web service, without using the WSDL or “Add Service Reference” in Microsoft Visual Studio 2010. You can use the following functions:

/// <summary>
/// Execute a Soap WebService call
/// </summary>
public override void Execute()
{
HttpWebRequest request = CreateWebRequest();
XmlDocument soapEnvelopeXml = new XmlDocument();
soapEnvelopeXml.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
<soap:Body>
<HelloWorld3 xmlns=""http://tempuri.org/"">
<parameter1>test</parameter1>
<parameter2>23</parameter2>
<parameter3>test</parameter3>
</HelloWorld3>
</soap:Body>
</soap:Envelope>");
using (Stream stream = request.GetRequestStream()) 
{ 
soapEnvelopeXml.Save(stream); 
}
using (WebResponse response = request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream())) 
{ 
string soapResult = rd.ReadToEnd();
Console.WriteLine(soapResult);
} 
}
}
/// <summary>
/// Create a soap webrequest to [Url]
/// </summary>
/// <returns></returns>
public HttpWebRequest CreateWebRequest()
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@"http://dev.nl/Rvl.Demo.TestWcfServiceApplication/SoapWebService.asmx"); 
webRequest.Headers.Add(@"SOAP:Action"); 
webRequest.ContentType = "text/xml;charset=\"utf-8\""; 
webRequest.Accept = "text/xml"; 
webRequest.Method = "POST"; 
return webRequest; 
}

Result

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><HelloWorld3Response xmlns="http://tempuri.org/"><HelloWorld3Result>test</HelloWorld3Result></HelloWorld3Response></soap:Body></soap:Envelope>

 

You can use complex types in you’re request. I use fiddler to get the contents of the soap envelope.

Leave a Reply

Your email address will not be published. Required fields are marked *

35 comments

  1. Manaat says:

    Can you please provide me a sample how to read a soap request in a webservice and and then create a soap resapone(data id fetched from datatbase then a soap response will be created) and send across

  2. Johan Veldkamp says:

    Hai There,

    Could you please sent me some example code inclusive the asp.net from which it is called?

  3. lemorlenny says:

    Hi, I receive some errors in this script, what’s the required #using I need to include?.

    regards

  4. vitdonal says:

    I have a problem. I call a soap webservice and use code above , I met an error in this line “using (WebResponse response = request.GetResponse())”. Error content is “The remote server returned an error: (500) Internal Server Error.”. Can everybody can help me solve this problem. Thanks!

  5. baris says:

    Actually, the soap message header does not work. What I have done is to add it to the content area. See my function that actually works:
    public HttpWebRequest CreateWebRequest(string url, string soapAction)
    {
    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
    webRequest.ContentType = “application/soap+xml;charset=UTF-8;action=\””+ soapAction + “\””;
    webRequest.Method = “POST”;
    return webRequest;
    }

  6. shyamal says:

    what is sopaAction here ?

    action=\””+ soapAction + “\””;

  7. Jaydipsinh Gharia says:

    i am using above code but in response how do i know that my request is successfully done and method executed?

  8. Thanks for this code. I was looking for something similar.

  9. Jakob Krarup says:

    Just what I needed. VS2010 wouldn’t create proxyclasses for a Java webservice for some reason, so I am using raw XML – thanks! 🙂

  10. firebird says:

    Thanks for this code. I was looking for something similar.

  11. harshil says:

    @ shyamal
    soapAction is SOAP:Action
    @baris
    the function you gave worked!!!!!
    @everyone
    cal baris’ function like :
    HttpWebRequest request = CreateWebRequest(“http://url”,”SOAP:Action”);

  12. Dom says:

    How does this work? When using:

    webRequest.Headers.Add(@”SOAP:Action”);
    webRequest.ContentType = “text/xml;charset=\”utf-8\””;

    I get this : (500) Internal Server Error

    When using:

    webRequest.ContentType = “application/soap+xml;charset=UTF-8;action=\”SOAP:Action\””;

    I get this:

    The remote server returned an error: (415) Cannot process the message because the content type ‘application/soap+xml;charset=UTF-8;action=”SOAP:Action”‘ was not the expected type ‘text/xml; charset=utf-8’..

    How do I get this to work?

  13. krishan says:

    Can you please provide me a sample how to make a dynamic soap request from database and then how to call a webservice and read a soap response and save it to database

  14. DIY says:

    @krishan The answer is Yes

  15. Ivan says:

    Thanks, very helpful code!

  16. Sanket says:

    please provide me the code i got below error
    The remote server returned an error: (415) Cannot process the message because the content type
    after adding
    ‘application/soap+xml;charset=UTF-8;action=”SOAP:Action”‘ was not the expected type ‘text/xml; charset=utf-8′..

  17. prashanth M says:

    string parameter3=”test”;
    soapEnvelopeXml.LoadXml(@”

    test
    23
    ?????—>here i want to pass user defined parameter value instead hardcoded test how can pass it here

    “);
    —->>>>>>>>>>—–>>>>>>>>>>
    ?????—>here i want to pass user defined parameter value which i have defined top instead hardcoded test value how can pass it here? i tried using
    “+parameter3+”—> but i am getting compile time error ..how can i pass this value here ??

  18. prashanth M says:

    string parameter3=”test”;
    ?????—>here i want to pass user defined parameter value which i have defined top instead hardcoded test value how can pass it here? i tried using
    “+parameter3+”—> but i am getting compile time error ..how can i pass this value here ??

  19. ravi says:

    Hi Dom or Sankat

    Did you get any solution for that please share it if you have. I’m also facing the same problem (500) Internal Server Error or (415) Cannot process.

    Thanks in advance.

  20. paulo says:

    Hi I am having an error “The remote server returned an error(400) bad request”. when i am on “WebResponse response = request.GetResponse()”. what should i do on this kind of error?

  21. Fred McGriff says:

    Thanks, You got me on the right track.
    I needed to add a name space to the Envelope:
    xmlns:ns1=””http://www.foo.com””

    I had to add my own body stuff:
    myparm

    And I had to add:

    using System.Xml;
    using System.IO;
    using System.Net;

    And I added a
    Console.ReadKey();
    on the end.

    And it worked!!!

    Thanks from the internet!

  22. Mithilesh says:

    Hello,

    I am trying to call web Service. I followed the above step and I am getting error as

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

    please help

  23. Sky says:

    This is how i got it to work.

    Used fiddle to see the Request Headers, added them to the public HttpWebRequest CreateWebRequest()like below:

    I also added a The X509 certificate comes before the HTTP webRequest.

    public HttpWebRequest CreateWebRequest()
    {

    //The X509 certificate comes before the HTTP webRequest.
    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

    HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(@”endpoint here”);
    webRequest.Headers.Add(@”SOAPAction: PerformRiskProductGenericCalculation”);
    webRequest.ContentType = “text/xml;charset=\”utf-8\””;
    webRequest.Accept = “gzip,deflate”;
    webRequest.UserAgent = “Apache-HttpClient/4.1.1 (java 1.5)”;
    webRequest.Method = “POST”;
    return webRequest;
    }

  24. Baseer says:

    I am getting 500 Internal Server error, I am Calling SOAP service on HTTPS I have already added following code

    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);

    please some body help me out???

  25. Jazzkatua says:

    Nice workaround for a faulty WSDL I have 😉

  26. Hi,

    Thank you for the article. Please have in consideration the following:
    You forgot to call the Close method. This will close the stream and release the connection. Failure to do so may cause your application to run out of connections.

    More details on:
    https://msdn.microsoft.com/en-US/library/system.net.httpwebrequest.getresponse(v=vs.110).aspx
    https://msdn.microsoft.com/en-US/library/system.net.httpwebresponse.close(v=vs.110).aspx

  27. Fernando Kodama says:

    Hi Roel!

    It works here! Thank you for sharing!

    Awesome!

    Fernando

  28. Duy Nguyen says:

    Hi Roel,

    This code seems working http only. how about “https”? I always get error, could you have any idea for it?

    Thanks,
    Duy.Nguyen

  29. Jim says:

    Thanks for sharing! Quick and easy!

  30. Emam says:

    Getting response as
    CollabNet
    Hi there, this is an AXIS service!
    Perhaps there will be a form for invoking the service here…

    Kindly help me.

  31. evaldo junior says:

    public partial class MainPage : PhoneApplicationPage{
    wsServico.cadastroTo cadastroTo = null;
    I am new to C #, my Visual Studio is 10 for Windows Phone, my version of Windows Phone 7 is researched on the internet and in this version of the command “async” only works Visual Studio 12 up. You have any other alterantiva?
    The Web Service is written in Java and runs on Jboss.
    I can map the wsdl webservice with references service, but the return is always zero, but in Android works, and a desktop application C # also works which the error can be?

    The following source code:
    public MainPage(){
    InitializeComponent();
    }

    private void button1_Click(object sender, RoutedEventArgs e){
    wsServico.TesteJavaWsClient ws = new wsServico.TesteJavaWsClient();
    ws.returnServicoAsync(“A”, “B”);
    ws.returnServicoCompleted += new EventHandler(ws_returnServicoCompleted);

    }

    void ws_returnServicoCompleted(object sender,
    wsServico.returnServicoCompletedEventArgs e){
    cadastroTo = e.Result;
    textBox1.Text = cadastroTo.cadastroId.ToString();
    }

    }

  32. Rodrigo says:

    Maaaaan you just saved my live, thank you very very much!!!

  33. Beartooth says:

    Thanks for this. And thank you posters for additional information.

    I was just starting to work on something similar and am glad you validated this method. As is so, so typical with Microsoft, they create APIs that are MUCH too low-level (COM, Extended MAPI, etc), both of which have some 500 methods and dozens of classes and interfaces. If all you have to do is send a simple SOAP envelope and message that you code yourself and receive a single field in response it is massive overkill to feed the WSDL doc to wsdl.exe or svcutil.exe (which, oddly, produce quite different SOAP proxy clients) or use the WSDL file with Add Service Request.

    In early .NET, you only needed a SoapClient-derived class, a SoapEnvelope class and an XmlReader. Now MS generates proxies that are hundreds of lines long and, in one module, include every exotic method for sending SOAP messages under every imaginable condition or need. Typical MS (sigh…).

    I started programming mainframe assembly in the 70s. Moved on to many other languages (C and 80×86 asm since 1981, C++ since ’85, Java since ’96, etc.). When C# and Java first came out, they were relatively elegant highly-abstracted languages – especially if you already had low-level language experience and knew what the computer was actually turning your intermediate code into!!! However, over the years, both C# and Java have gradually become so bloated that today’s newly-written commercial web-based enterprise software is actually running slower each year because high-level programmers and bloated frameworks and language additions have slowed down execution faster than CPUs have increased in speed. Now, I mostly use Java and .NET and programming has become more of a chore than an artistic endeavor (sigh…). Thanks for removing some of the chore.

  34. Rudolf says:

    Thank you!
    Worked for me.