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
Step 2
Right click on the solution and go to
Add >
New Project.
Step 3Go 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.
- private async void getResponsebtn_Click(object sender, EventArgs e)
- {
- HttpClient httpClient = new HttpClient();
- XNamespace xmlNamepace = XNamespace.Get("http://schemas.microsoft.com/2003/10/Serialization/");
- string response = await httpClient.GetStringAsync("http://localhost:49733/WelcomeWCFService.svc/Welcome/" + getNametb.Text);
- XDocument xmlResponse = XDocument.Parse(response);
- MessageBox.Show(xmlResponse.Element(xmlNamepace + "string").Value, "Welcome");
- }
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.
XNamespaceIt 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