Creating WCF Service With WsHttpBinding and Consuming in Web Application

This article provides an example using WCF. After going through this snippet, the reader will have a clear and basic understanding of the wsHttpBinding and how to consume it in a web application.

  1. Visual Studio 2010
  2. SQL Server 2008 SSMS

Step 1

Open Visual Studio 2010 and add a new project named PincodeService. Then add a WCF Service file named DataService.svc as in the following:



Step 2

In that, you will see [ServiceContract]. Below this your interface name is declared. Thereafter you'll see [OperationContract]; your function contract should be defined here.





Step 3

Implementation of interface methods.

DataService.cs contains the following code.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Data.SqlClient;  
  6. using System.Linq;  
  7.   
  8. namespace PincodeService  
  9. {  
  10.     // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "DataService" in code, svc and config file together.  
  11.     public class DataService : IDataService  
  12.     {  
  13.         List<PinCode> IDataService.getPincodeDetails(string pinCode)  
  14.         {  
  15.             List<PinCode> lstPinCode = new List<PinCode>();  
  16.             DataTable dsData = new DataTable();  
  17.             dsData = getPincode(pinCode);  
  18.   
  19.             if (dsData != null)  
  20.             {  
  21.                 foreach (DataRow row in dsData.Rows)  
  22.                 {  
  23.                     PinCode objPincode = new PinCode();  
  24.                     objPincode.Pincode = Convert.ToString(row["Pincode"]);  
  25.                     objPincode.PostOfficeName = Convert.ToString(row["Post_Office_Name"]);  
  26.                     objPincode.DistrictName = Convert.ToString(row["Districts_Name"]);  
  27.                     objPincode.CityName = Convert.ToString(row["City_Name"]);  
  28.                     objPincode.State = Convert.ToString(row["State"]);  
  29.                     lstPinCode.Add(objPincode);  
  30.                 }  
  31.             }  
  32.   
  33.             return lstPinCode.ToList();  
  34.         }  
  35.  
  36.  
  37.         #region " [ Private Function ] "  
  38.         private DataTable getPincode(string pinCode)  
  39.         {  
  40.             DataSet dsData = new DataSet();  
  41.             SqlConnection sqlCon = null;  
  42.             SqlDataAdapter sqlCmd = null;  
  43.   
  44.             try  
  45.             {  
  46.                 using (sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString))  
  47.                 {  
  48.                     sqlCmd = new SqlDataAdapter("USP_PINCODECRUD", sqlCon);  
  49.                     sqlCmd.SelectCommand.CommandType = CommandType.StoredProcedure;  
  50.                     sqlCmd.SelectCommand.Parameters.AddWithValue("@PINCODE", pinCode);  
  51.   
  52.                     sqlCon.Open();  
  53.                     sqlCmd.Fill(dsData);  
  54.   
  55.                     sqlCon.Close();  
  56.                 }  
  57.             }  
  58.             catch  
  59.             {  
  60.                 throw;  
  61.             }  
  62.             return dsData.Tables[0];  
  63.         }  
  64.         #endregion  
  65.     }  
  66. }  

Step 4

The following describes the DataTable and Stored Procedure used.

The following is the database script included in the download:


  1. CREATE PROCEDURE [USP_PINCODECRUD]  
  2.     @PINCODE        VARCHAR(6)  
  3. AS  
  4. BEGIN  
  5.     SELECT Pincode, Post_Office_Name, Districts_Name, City_Name, [State]  
  6.     FROM tbl_PincodeMaster  
  7.     WHERE Pincode LIKE '%' + @PICODE + '%'  
  8. END  
  9. GO  

Step 5

Change the web config in the system service model as in the following:

  1. <?xml version="1.0"?>  
  2. <configuration>  
  3.   
  4.   <system.web>  
  5.     <compilation debug="true" targetFramework="4.0" />  
  6.   </system.web>  
  7.   
  8.   <connectionStrings >  
  9.     <add name="connectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient"/>  
  10.   </connectionStrings>  
  11.   
  12.   <system.serviceModel>  
  13.   
  14.     <services>  
  15.   
  16.       <service name="PincodeService.DataService" >  
  17.         <endpoint address="PincodeService" binding="wsHttpBinding" contract="PincodeService.IDataService"/>  
  18.         <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>  
  19.         <host>  
  20.           <baseAddresses >  
  21.             <add  baseAddress="http://localhost:8080/"/>  
  22.           </baseAddresses>  
  23.         </host>  
  24.       </service>  
  25.     </services>  
  26.       
  27.     <behaviors>  
  28.       <serviceBehaviors>  
  29.         <behavior>  
  30.           <serviceMetadata httpGetEnabled="true"/>  
  31.           <serviceDebug includeExceptionDetailInFaults="false"/>  
  32.         </behavior>  
  33.       </serviceBehaviors>  
  34.     </behaviors>  
  35.     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  
  36.   </system.serviceModel>  
  37.     
  38.   <system.webServer>  
  39.     <modules runAllManagedModulesForAllRequests="true"/>  
  40.   </system.webServer>  
  41. </configuration>  

Step 6

Compile and run the WCF application.





Step 7

Consuming the Service and using it in the web application.

Open another Visual Studio 2010 instance and add an empty web project as WcfClientUI.

The Service will be consumed and used in this application.



Right-click on the project and service reference and provide the address of the service. Add the discovered service to the project.





Step 8

I have added one aspx web page.

The following is the Service proxy created and used to access the exposed methods.

  1. #region " [ namespaces ] "  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. #endregion  
  6.   
  7. public partial class _Default : System.Web.UI.Page  
  8. {  
  9.     protected void Page_Load(object sender, EventArgs e)  
  10.     {  
  11.     }  
  12.  
  13.     #region " [ Button Events ] "  
  14.     protected void btnSubmit_Click(object sender, EventArgs e)  
  15.     {  
  16.         PincodeService.DataServiceClient objService = new PincodeService.DataServiceClient();  
  17.         List<PincodeService.PinCode> lstPincode = new List<PincodeService.PinCode>();  
  18.   
  19.         lstPincode = objService.getPincodeDetails(txtPincode.Text.Trim()).ToList();  
  20.   
  21.         gvData.DataSource = lstPincode;  
  22.         gvData.DataBind();  
  23.   
  24.     }  
  25.     #endregion  
  26. }  
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title>Pincode Client</title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.     <div>  
  11.         <table width="40%">  
  12.             <tr>  
  13.                 <td colspan="3" align="center">  
  14.                     <asp:Label ID="lblMsg" runat="server" ForeColor="Red"></asp:Label>  
  15.                 </td>  
  16.             </tr>  
  17.             <tr>  
  18.                 <td>  
  19.                     Pincode  
  20.                 </td>  
  21.                 <td>  
  22.                     <asp:TextBox ID="txtPincode" runat="server" MaxLength="6" AutoCompleteType="Disabled"></asp:TextBox>  
  23.                 </td>  
  24.                 <td align="left">  
  25.                     <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />  
  26.                 </td>  
  27.             </tr>  
  28.             <tr>  
  29.                 <td>  
  30.                     <br />                    <br />                    <br />  
  31.                 </td>  
  32.             </tr>  
  33.             <tr>  
  34.                 <td colspan="3">  
  35.                     <asp:GridView ID="gvData" runat="server" AutoGenerateColumns="true" EmptyDataText="No data found."  
  36.                         EmptyDataRowStyle-ForeColor="Red">  
  37.                     </asp:GridView>  
  38.                 </td>  
  39.             </tr>  
  40.         </table>  
  41.     </div>  
  42.     </form>  
  43. </body>  
  44. </html>  

Step 9

Compile and run the client application.




Similar Articles