Saturday 3 August 2019

Call (Consume) REST WCF Service (SVC) in Console Application using C# and VB.Net

In this article I will explain with an example, how to call (consume) REST WCF Service (SVC) in Console Application using C# and VB.Net.
This Rest WCF Service (SVC) will be called in Console Application using WebClient class in C# and VB.Net.
Adding Service to Project
The very first thing you need to do is add a WCF service to your project by clicking on Add New Items as shown below.
Call (Consume) REST WCF Service (SVC) in Console Application using C# and VB.Net
Configuring the WCF Service
A new Endpoint Behavior named ServiceHttpBehavior is added to the Web.Config. This behavior will set the binding to WebHttpBinding, which is very important in order to accessing WCF Service using HTTP methods.
<system.serviceModel>
  <behaviors>
    <serviceBehaviors>
      <behavior name="ServiceBehavior">
        <serviceMetadata httpGetEnabled="true"/>
        <serviceDebug includeExceptionDetailInFaults="false"/>
      </behavior>
    </serviceBehaviors>
    <endpointBehaviors>
      <behavior name="ServiceHttpBehavior">
        <enableWebScript/>
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
  <services>
    <service behaviorConfiguration="ServiceBehavior" name="Service">
      <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="ServiceHttpBehavior">
      </endpoint>
      <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
    </service>
  </services>
</system.serviceModel>
Building the WCF Service Method
The IService Interface has a method GetData which is decorated with OperationContract attribute.
The IService Interface has been implemented in a class named Service which contains the definition of the GetData method.
This method accepts the Name and Age parameters and then wraps them into a JSON object along with the Current DateTime and returns it back in the form of serialized JSON string.
C#
IService.cs
using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web.Script.Serialization;
[ServiceContract]
public interface IService
{
    [OperationContract]
    string GetData(string name, int age);
}
Service.cs
using System;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Web.Script.Serialization;
public class Service : IService
{
    public string GetData(string name, int age)
    {
        object data = new
                        {
                            Name = name,
                            Age = age,
                            TimeStamp = DateTime.Now.ToString()
                        };
        return (new JavaScriptSerializer().Serialize(data));
    }
}
VB.Net
IService.vb
Imports System.ServiceModel
<ServiceContract()>
Public Interface IService
    <OperationContract()>
    Function GetData(name As String, age As IntegerAs String
End Interface
Service.vb
Imports System.Web.Script.Serialization
Public Class Service
    Implements IService
    Public Function GetData(name As String, age As IntegerAs String Implements IService.GetData
        Dim data As Object = New With { _
                         .Name = name, _
                         .Age = age, _
                         .TimeStamp = DateTime.Now.ToString() _
        }
        Return (New JavaScriptSerializer().Serialize(data))
    End Function
End Class
Namespaces
You will need to import the following namespaces.
C#
using System.Text;
using System.Net.Http;
using System.Web.Script.Serialization;
VB.Net
Imports System.Text
Imports System.Net.Http
Imports System.Web.Script.Serialization
Call (Consume) REST WCF Service (SVC) in Console Application
Inside the Main method, the captured values of Name and Age are wrapped into a JSON object which is then serialized into a JSON string.
Note: In order to use JavaScriptSerializer class in Console Application, please refer my article: Using JavaScriptSerializer in Console Applications in C# and VB.Net.
The URL of the WCF Service along with its method and the serialized JSON string is passed to the UploadString method of the WebClient class.
The UploadString method of the WebClient class calls the WCF Service’s GetData method and returns the JSON string which is then displayed as Output in the Console Application.
C#
static void Main(string[] args)
{
    Console.Write("Enter Name: ");
    string name = Console.ReadLine();
    Console.Write("Enter Age: ");
    string age = Console.ReadLine();
    string serviceUrl = "http://localhost:17154/CS/Services/Service.svc";
    object input = new
    {
        name = name,
        age = age
    };
    string inputJson = (new JavaScriptSerializer()).Serialize(input);
    WebClient client = new WebClient();
    client.Headers["Content-type"] = "application/json";
    client.Encoding = Encoding.UTF8;
    string output = client.UploadString(serviceUrl + "/GetData", inputJson);
    Console.WriteLine("Output: " + output);
    Console.ReadLine();
}
VB.Net
Sub Main()
    Console.Write("Enter Name: ")
    Dim name As String = Console.ReadLine()
    Console.Write("Enter Age: ")
    Dim age As String = Console.ReadLine()
    Dim serviceUrl As String = "http://localhost:17157/VB/Services/Service.svc"
    Dim input As Object = New With { _
                    .name = name, _
                    .age = age _
    }
    Dim inputJson As String = (New JavaScriptSerializer()).Serialize(input)
    Dim client As New WebClient()
    client.Headers("Content-type") = "application/json"
    client.Encoding = Encoding.UTF8
    Dim output As String = client.UploadString(serviceUrl & "/GetData", inputJson)
    Console.WriteLine("Output: " + output)
    Console.ReadLine()
End Sub

No comments:

Post a Comment