Create A WCF Service Client In Visual Studio 2015

This article will demonstrate how you can create a .NET client for consuming REST based WCF Web Service, which returns response in an XML format.

Step 1

Create a REST based WCF Service, which returns a response in an XML format or if you have no idea, then create a WCF Service as demonstrated in the article Create WCF Web Service In Visual Studio 2015.

Step 2

Right click on the solution and go to Add > New Project.



Step 3

Go to Installed > Windows and select Windows Forms Application. Write RESTXmlWelcomeWCFServiceClient, choose the location for your project and click OK.
 

Step 4

Drag and drop a button from Toolbox.



Step 5

Change the Name and Text of the button from property Window, as shown below.

 

Step 6

Drag and drop a TextBox from Toolbox.

 

Step 7

Change the Name of TextBox from property Window, as shown below.

 

Step 8

Select the button from designer Window and double click it.
 
 

Step 9

Form1.cs file will open. Replace the getResponsebtn_Click method code with the lines given below.
  1. private async void getResponsebtn_Click(object sender, EventArgs e)
  2. {
  3. HttpClient httpClient = new HttpClient();
  4. XNamespace xmlNamepace = XNamespace.Get("http://schemas.microsoft.com/2003/10/Serialization/");
  5. string response = await httpClient.GetStringAsync("http://localhost:49733/WelcomeWCFService.svc/Welcome/" + getNametb.Text);
  6. XDocument xmlResponse = XDocument.Parse(response);
  7. MessageBox.Show(xmlResponse.Element(xmlNamepace + "string").Value, "Welcome");
  8. }

HttpClient

It provides the methods to invoke WCF Service. In the code given above, GetStringAsync method of HttpClient (takes the URL as a parameter, which is used to send the request to the Service) invokes the Service and returns its response.

XNamespace

It is used to get the value of xmlns(XMl message namespace), which is required to access XML elements from Response. You can obtain xmlns value by seeing your Service response in the browser (just right click on your Service svc file and choose view in the Browser), as shown below.

 
XDocument

It provides the methods to parse XML. In the code XDocument Parse method will parse the returned XML response and Element method will get the value of specific element.

Step 10

Right click on your Windows Forms Application project and set it as a startup project



Step 11

Start your project

 

Step 12

A window will be open enter the text in the TextBox and click GetResponse button

 

If you show a pop up window with message as shown in figure than you have successfully created a client for your service

 

Up Next
    Ebook Download
    View all
    Learn
    View all