42 Comments

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.

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

  1. 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. Hai There,

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

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

    regards

  4. 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. 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. i am using above code but in response how do i know that my request is successfully done and method executed?

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

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

  9. 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?

  10. 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

  11. 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′..

  12. 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 ??

  13. 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 ??

  14. 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.

  15. 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?

  16. 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!

  17. 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

  18. 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;
    }

  19. 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???

  20. 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

  21. 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.

  22. 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();
    }

    }

  23. 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.

  24. Hi,
    I am getting below error.

    The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel

  25. I kept getting error 500 and saying a ProLog error.
    i fixed it by not putting the soapEnvelopeXml in an XMLDocument.
    I put it in an Encoded UTF8 string and put it in the stream that way which made it work.

  26. Hi Roel van Lisdonk,

    I have tried with same code in my application , but when I’m trying to give XML request, it’s return ” Error security Header! ” error message. i have already added Header messages , Security and Nonce. Even it’s return error message.
    Thank You.

  27. Hi,
    I am new for the developments with web services. I have tried to call a java web service with what you have posted here, but I`m getting an error saying “Please enable REST support in WEB-INF/conf/axis2.xml and WEB-INF/web.xml”.

  28. Thanks ! … This was helpful ! and worked ..

    Am also looking for articles on example C# code calling REST web services.
    not so easy … yet ..

  29. Hi,

    This works perfectly fine.
    But I am still unsure why one would not want to use Proxy classes (except in cases where there is a need to read the response header)? Is there any performance boost we get when we use HttpClient/ HttpWebRequest instead of Proxy classes?

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts