SOAP - Adding Service Reference

What is a Service Reference?

  • A Service Reference in Visual Studio is a shortcut that lets you connect your C# project to a SOAP service.

  • Instead of writing raw XML SOAP requests manually, Visual Studio reads the WSDL file of the service and auto-generates a proxy client (C# classes) for you.

  • With this proxy, you can call SOAP operations as if they were normal C# methods.


How It Works (Step by Step)

  1. Get the WSDL URL

    • Example: http://example.com/hello.asmx?WSDL

  2. In Visual Studio

    • Right-click your project → AddService Reference…

    • Paste the WSDL URL.

    • Choose a namespace (e.g., HelloService).

    • Click OK.

  3. Visual Studio Generates Code

    • It creates C# classes (the proxy client) that match the service’s operations, inputs, and outputs.

  4. Use the Service in Code

    • Now you can call SOAP methods like this:

using (var client = new HelloService.HelloServiceClient())
{
    string response = client.SayHello("John");
    Console.WriteLine(response);
}

What’s Happening Behind the Scenes

  • Normally, a SOAP request looks like this (XML + HTTP headers):

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <SayHello xmlns="http://example.com/hello">
      <name>John</name>
    </SayHello>
  </soap:Body>
</soap:Envelope>
  • With a service reference, you don’t write this XML yourself.

  • The proxy client automatically:

    1. Serializes your C# object into XML.

    2. Sends it over HTTP.

    3. Reads the SOAP response.

    4. Deserializes it back into a C# object.


Advantages of Service Reference

  1. No manual XML handling → You work with C# objects instead.

  2. Strong typing → Proxy classes enforce data types as defined in WSDL.

  3. Faster development → Just call methods; don’t worry about SOAP envelopes.

  4. Error reduction → Fewer chances of mistakes compared to writing raw XML.


 In short:
Adding a Service Reference in Visual Studio is like plugging in a ready-made connector. You give it the WSDL, and it builds a strongly-typed C# client for you, so you can call SOAP methods just like normal methods in your code.