In this article I will explain with an example, how to call (consume) WCF Service (SVC) without adding Service Reference in ASP.Net using C# and VB.Net.
The WCF Service (SVC) can be called (consumed) without adding Service Reference by making use of the ChannelFactory class in ASP.Net.
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
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.
Building the WCF Service
The next task is to add the OperationContract method to the WCF Service that will fetch the records from the database and will act as a source of data for the GridView.
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.ServiceModel;
using System.Runtime.Serialization;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.ServiceModel
Imports System.Runtime.Serialization
IService Interface
The IService Interface class has a DataContract class named CustomerData which contains a DataTable Property CustomersTable which will be used to send the data from the WCF Service to the Web Application.
The IService Interface has a method GetCustomers which is decorated with OperationContract attribute.
C#
[ServiceContract]
public interface IService
{
[OperationContract]
CustomerData GetCustomers(int customerId);
}
[DataContract]
public class CustomerData
{
public CustomerData()
{
this.CustomersTable = new DataTable("CustomersData");
}
[DataMember]
public DataTable CustomersTable { get; set; }
}
VB.Net
<ServiceContract()> _
Public Interface IService
<OperationContract()> _
Function GetCustomers(customerId As Integer) As CustomerData
End Interface
<DataContract()> _
Public Class CustomerData
Public Sub New()
Me.CustomersTable = New DataTable("CustomersData")
End Sub
<DataMember()> _
Public Property CustomersTable() As DataTable
Get
Return m_CustomersTable
End Get
Set(value As DataTable)
m_CustomersTable = value
End Set
End Property
Private m_CustomersTable As DataTable
End Class
Service Class
The IService Interface has been implemented in a class named Service which contains the definition of the GetCustomers method.
This method gets the records from the Customers table and populates the DataTable of the CustomerData class object which finally is returned to the client accessing the WCF service.
C#
public class Service : IService
{
public CustomerData GetCustomers(int customerId)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string sql = "SELECT CustomerId, Name, Country FROM Customers";
if (customerId > 0)
{
sql += " WHERE CustomerId = @CustomerId";
}
using (SqlCommand cmd = new SqlCommand(sql))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
if (customerId > 0)
{
cmd.Parameters.AddWithValue("@CustomerId", customerId);
}
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
CustomerData customers = new CustomerData();
sda.Fill(customers.CustomersTable);
return customers;
}
}
}
}
}
}
VB.Net
Public Class Service
Implements IService
Public Function GetCustomers(customerId As Integer) As CustomerData Implements IService.GetCustomers
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Dim sql As String = "SELECT CustomerId, Name, Country FROM Customers"
If customerId > 0 Then
sql += " WHERE CustomerId = @CustomerId"
End If
Using cmd As New SqlCommand(sql)
Using sda As New SqlDataAdapter()
cmd.Connection = con
If customerId > 0 Then
cmd.Parameters.AddWithValue("@CustomerId", customerId)
End If
sda.SelectCommand = cmd
Using dt As New DataTable()
Dim customers As New CustomerData()
sda.Fill(customers.CustomersTable)
Return customers
End Using
End Using
End Using
End Using
End Function
End Class
HTML Markup
The HTML Markup consists of a TextBox, a Button and a GridView.
CustomerId:
<asp:TextBox ID="txtCustomerId" runat="server" />
<asp:Button ID="btnSearch" Text="Search" runat="server" OnClick="Search" />
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="Customer Id" ItemStyle-Width="150" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="100" />
</Columns>
</asp:GridView>
Call (Consume) WCF Service without adding Service Reference
The GetServiceClient method
The GetServiceClient method is used to access the WCF Service without adding its Service Reference. Inside this method, first an object of BasicHttpBinding is created and then an object of EndPointAddress is created using the URL of the WCF service which is passed as parameter to its Constructor.
Note: You can get the URL of the WCF Service by right clicking the Service.svc file from the Solution Explorer and then clicking the View in Browser option from the context menu.
Now these two objects i.e. BasicHttpBinding and EndPointAddress are passed as parameter to the CreateChannel method of the ChannelFactory class which returns the object of type IService i.e. the interface of WCF service.
Page Load
Inside the Page Load event handler, the object of type IService interface is returned by the GetServiceClient method.
Using the object of type IService interface, the GetCustomers method is accessed and the customerId parameter value is passed 0 which fetches all the records present in the database table.
The fetched records are present in the CustomersTable DataTable which is ultimately used to populate the GridView control.
Button Click
Inside the Button Click event handler, the object of type IService interface is returned by the GetServiceClient method.
Using the object of type IService interface, the GetCustomers method is accessed and the value of the CustomerId TextBox is passed as parameter which fetches the specific records present in the database table based on CustomerId.
The fetched record is present in the CustomersTable DataTable which is ultimately used to populate the GridView control.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
IService client = this.GetServiceClient();
GridView1.DataSource = client.GetCustomers(0).CustomersTable;
GridView1.DataBind();
}
}
protected void Search(object sender, EventArgs e)
{
int customerId;
int.TryParse(txtCustomerId.Text.Trim(), out customerId);
IService client = this.GetServiceClient();
GridView1.DataSource = client.GetCustomers(customerId).CustomersTable;
GridView1.DataBind();
}
private IService GetServiceClient()
{
BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress endpoint = new EndpointAddress("http://localhost:8744/CS/Service.svc");
IService client = ChannelFactory<IService>.CreateChannel(binding, endpoint);
return client;
}
VB.Net
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim client As IService = Me.GetServiceClient()
GridView1.DataSource = client.GetCustomers(0).CustomersTable
GridView1.DataBind()
End If
End Sub
Protected Sub Search(sender As Object, e As EventArgs)
Dim customerId As Integer
Integer.TryParse(txtCustomerId.Text.Trim(), customerId)
Dim client As IService = Me.GetServiceClient()
GridView1.DataSource = client.GetCustomers(customerId).CustomersTable
GridView1.DataBind()
End Sub
Private Function GetServiceClient() As IService
Dim binding As New BasicHttpBinding()
Dim endpoint As New EndpointAddress("http://localhost:8747/VB/Service.svc")
Dim client As IService = ChannelFactory(Of IService).CreateChannel(binding, endpoint)
Return client
End Function
Screenshot
Demo
Downloads