Using a SOAP service in .NET

In this article I’ll describe how to consume a SOAP service in a .NET application. We’ll write the service itself in PHP, but the manner in which the service is written doesn’t matter. It looks like this (I’m using the NuSoap library)

	function getPeople($age)
		$people = array(
			array('Name' => "Magnus Ferm", 'Age' => 27, 'Gender' => 'Male'),
			array('Name' => "Nils Pils", 'Age' => 48, 'Gender' => 'Male'),
			array('Name' => "Per Bers", 'Age' => 52, 'Gender' => 'Male'),
			array('Name' => "Inga Lundh", 'Age' => 42, 'Gender' => 'Female'),
			array('Name' => "Jessie Presley", 'Age' => 18, 'Gender' => 'Female')
		$filteredPeople = array();
		foreach($people as $person)
			if($person['Age'] < $age)
				array_push($filteredPeople, $person);
		return $filteredPeople;
	$namespace = "";
	$server = new soap_server();
	$server->wsdl->schemaTargetNamespace = $namespace;
			'Name' => array('name' => 'Name', 'type' => 'xsd:string'),
			'Age' => array('name' => 'Age', 'type' => 'xsd:int'),
			'Gender' => array('name' => 'Gender', 'type' => 'xsd:string')
			array('ref' => 'SOAP-ENC:arrayType', 'wsdl:arrayType' => 'tns:Person[]')
					// method name:
					// parameter list:
					// return value(s):
					// namespace:
					// soapaction: (use default)
					// style: rpc or document
					// use: encoded or literal
					// description: documentation for the method
					'Returns a list of people under the age of X');
	// Get our posted data if the service is being consumed
	// otherwise leave this data blank.                
	// pass our posted data (or nothing) to the soap service                    

This service gives you access to a method called ‘getPeople’ which takes one parameter, max age. This is not the most useful service and will only serve as a an example.
To call this service we’ll create a new project in Visual Studio. I’ve chosen a console project and to add the service we’ll do as follows:

Right click on References and select 'Add Service Reference'

Chose 'Advanced'
Choose 'Add Web Reference'
Type the address to the service, don't forget the ?wsdl-suffix and press 'Add Reference'

Now we’ve created a connection to our webservce and we should see the following in our solution explorer:

Now we can see our service in the solution explorer

If we are going to use the service we have to add a reference in the file we’re using:

using System;
namespace WebServiceTest
    class Program
        static void Main(string[] args)
            PeopleService service = new PeopleService();
            var people = service.getPeople(30);
            foreach (Person person in people)
                Console.WriteLine("Name: {0}, Age: {1}", person.Name, person.Age);
Here we have a filtered list of people from the service