In this article I will explain with an example, how to call (consume) REST WCF Service (SVC) using HttpWebRequest 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 HttpWebRequest 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
Namespaces
You will need to import the following namespaces.
C#
using System.Net;
using System.Text;
using System.Web.Script.Serialization;
VB.Net
Imports System.Net
Imports System.Text
Imports System.Web.Script.Serialization
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>
Call (Consume) REST WCF Service (SVC) using HttpWebRequest 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.
A new object of the HttpWebRequest class, and the URL of the WCF Service along with its method is passed as parameter.
Then the serialized JSON string is converted to Byte array using UTF8 Encoding.
Now a HTTP POST request is made using the GetRequestStream method of the HttpWebRequest class.
Finally the response is received into a Stream class object by making use of the GetResponseStream method of the HttpWebRequest class.
The Stream class object is read using StreamReader and is displayed using the Label control.
C#
protected void Submit(object sender, EventArgs e)
{
string serviceUrl = "http://localhost:17754/CS/Services/Service.svc";
object input = new
{
name = txtName.Text.Trim(),
age = txtAge.Text.Trim()
};
string inputJson = (new JavaScriptSerializer()).Serialize(input);
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(serviceUrl + "/GetData"));
httpRequest.Accept = "application/json";
httpRequest.ContentType = "application/json";
httpRequest.Method = "POST";
byte[] bytes = Encoding.UTF8.GetBytes(inputJson);
using (Stream stream = httpRequest.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
stream.Close();
}
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
using (Stream stream = httpResponse.GetResponseStream())
{
lblOutput.Text = (new StreamReader(stream)).ReadToEnd();
}
}
}
VB.Net
Protected Sub Submit(sender As Object, e As EventArgs)
Dim serviceUrl As String = "http://localhost:17757/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 httpRequest As HttpWebRequest = DirectCast(WebRequest.Create(New Uri(serviceUrl & "/GetData")), HttpWebRequest)
httpRequest.Accept = "application/json"
httpRequest.ContentType = "application/json"
httpRequest.Method = "POST"
Dim bytes As Byte() = Encoding.UTF8.GetBytes(inputJson)
Using stream As Stream = httpRequest.GetRequestStream()
stream.Write(bytes, 0, bytes.Length)
stream.Close()
End Using
Using httpResponse As HttpWebResponse = DirectCast(httpRequest.GetResponse(), HttpWebResponse)
Using stream As Stream = httpResponse.GetResponseStream()
lblOutput.Text = (New StreamReader(stream)).ReadToEnd()
End Using
End Using
End Sub
No comments:
Post a Comment