In this article I will explain with an example, how to call (consume) REST WCF Service (SVC) using HttpClient class in ASP.Net with C# and VB.Net.
This article will illustrate how to send and receive JSON data by doing HTTP POST to a JSON REST WCF Service (SVC) using HttpClient class in ASP.Net with 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.
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 Integer) As String
End Interface
Service.vb
Imports System.Web.Script.Serialization
Public Class Service
Implements IService
Public Function GetData(name As String, age As Integer) As 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
HTML Markup
The HTML Markup consists of two TextBoxes for capturing Name and Age values, a Button and a Label for displaying the returned JSON data.
<table border="0" cellpadding="2" cellspacing="0">
<tr>
<td>Name:</td>
<td><asp:TextBox ID="txtName" runat="server" /></td>
</tr>
<tr>
<td>Age:</td>
<td><asp:TextBox ID="txtAge" runat="server" /></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="Submit" /></td>
</tr>
<tr>
<td valign = "top">Output:
</td>
<td style = "width:255px;word-break:break-all">
<asp:Label ID="lblOutput" runat="server" Font-Names="courier new" />
</td>
</tr>
</table>
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) using HttpClient in ASP.Net
When the Submit Button is clicked, the values of the Name and Age TextBoxes are wrapped into a JSON object which is then serialized into a JSON string.
The URL of the WCF Service along with its method and the serialized JSON string is passed to the PostAsync method of the HttpClient class.
The PostAsync method of the HttpClient class calls the WCF Service’s GetData method and returns the JSON string which is then displayed in the Label.
C#
protected void Submit(object sender, EventArgs e)
{
string serviceUrl = "http://localhost:17154/CS/Services/Service.svc";
object input = new
{
name = txtName.Text.Trim(),
age = txtAge.Text.Trim()
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
HttpClient client = new HttpClient();
HttpContent inputContent = new StringContent(inputJson, Encoding.UTF8, "application/json");
HttpResponseMessage response = client.PostAsync(serviceUrl + "/GetData", inputContent).Result;
if (response.IsSuccessStatusCode)
{
lblOutput.Text = response.Content.ReadAsStringAsync().Result;
}
}
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
Dim serviceUrl As String = "http://localhost:17157/VB/Services/Service.svc"
Dim input As Object = New With { _
.name = txtName.Text.Trim(), _
.age = txtAge.Text.Trim() _
}
Dim inputJson As String = (New JavaScriptSerializer()).Serialize(input)
Dim client As New HttpClient()
Dim inputContent As HttpContent = New StringContent(inputJson, Encoding.UTF8, "application/json")
Dim response As HttpResponseMessage = client.PostAsync(serviceUrl & "/GetData", inputContent).Result
If response.IsSuccessStatusCode Then
lblOutput.Text = response.Content.ReadAsStringAsync().Result
End If
End Sub
No comments:
Post a Comment