consuming the RESTFul WCF service in client side example

Jan 28, 2013 00:00 · 250 words · 2 minute read Programming WCF

The client can simply use the WCF RESTFul service and invokes its methods remotely via WebChannelFactory.

Add reference

Firstly, we need to add a reference to the server side project so will have the same contacts in the client side . Also you need to add the System. ServiceModel.web name space to the client side to have the WebChannelFactory functionality .

Making a WebChannelFactory

It is getting the server side interface contract and the base address of hosting as input .

WebChannelFactoryC#

var factory =  new WebChannelFactory<IMachine>(new Uri("http://localhost:8080/RESTWcf"));
IMachine machine = factory.CreateChannel();

Calling methods

And then we can simply call the server side methods .
I just write a simple procedural functions to ask the user and run the methods.

client consoleC#

while (true) {
Console.WriteLine("To submit press 1 \nTo delete press 2 \nto Retrive press 3\n\n");
string readLine = Console.ReadLine();
	if (readLine.Equals("1")) {
		Console.WriteLine("please enter the machine name");
		string machineName = Console.ReadLine();
		var machineDetail = new MachineDetail {Name = machineName};
		string addMachine = machine.AddMachine(machineDetail);
		Console.WriteLine(addMachine);
	} else if (readLine.Equals("2")) {
		Console.WriteLine("please enter the machine Id that you want to delete");
		string machineId = Console.ReadLine();
		string deleteMachineById = machine.DeleteMachineById(machineId);
		Console.WriteLine(deleteMachineById);
	} else if (readLine.Equals("3")) {
		Console.WriteLine("please enter the machine Id that you want to get");
		string machineId = Console.ReadLine();
		string machineNameById = machine.GetMachineNameById(machineId);
		Console.WriteLine(machineNameById);
	} else {
		break;
	}
}

It goes through a loop and do the submit , delete and get functions.

Download

Feel free to download the full source code of this WCF example from my GitHub.