Web Services in ASP.Net C#

Web Services

Web Services are components on a web server that a client application can call by making HTTP requests across the Web. ASP.NET enables you to create custom Web Services or to use built-in application services and call these services from any client application.

Web Services communicate using the following standard web protocols and data formats:

  • HTTP
  • XML
  • SOAP

The following are some terms we often use with Web Services.

SOAP: Simple Object Access Protocol. SOAP is way by which method calls are translated into XML format and sent via HTTP.

WSDL: Web Service Description Language. WSDL contains every detail regarding the use of Web Services and method and properties provided by Web Service and URLs from which those methods can be accessed and data types used.

UDDI: Universal Description, Discovery and Integration (UDDI) is a directory service where businesses can register and search for Web Services.

Discovery or .Disco Files: The DISCO file typically points to a WSDL source that in turn points to the actual Web Service when one searches for the Web Services.

Now we will see how to create and consume Web Services in ASP.Net C#. The following is my data table in Design Mode from which I will fetch data using the Web Service:

table design
                                       Image 1.

The following is the script of my data table:

  1. CREATE TABLE [dbo].[Employee](  
  2.     [Emp_ID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [varchar](50) NULL,  
  4.     [Designation] [varchar](50) NULL,  
  5.     [City] [varchar](50) NULL,  
  6.     [State] [varchar](50) NULL,  
  7.     [Country] [varchar](50) NULL,  
  8.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED   
  9. (  
  10.     [Emp_ID] ASC  
  11. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]  
  12. ON [PRIMARY]  
  13. GO  
The following is the data in my table:

table
                                                                              Image 2.

Now open Visual Studio then select File -> New Web Site-> ASP.NET Web Service.

Web Service
                                                                        Image 3.

Now open Service.cs inside the App_Code folder to write your WebMethod as in the following:

WebMethod
                                                                        Image 4.

The following is the App_Code/Service.cs:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Services;  
  6. using System.Data.SqlClient;  
  7. using System.Data;  
  8. using System.Xml;  
  9.   
  10. [WebService(Namespace = "http://tempuri.org/")]  
  11. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  12. // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.   
  13. // [System.Web.Script.Services.ScriptService]  
  14. public class Service : System.Web.Services.WebService  
  15. {  
  16.     public Service()  
  17.     {  
  18.         //Uncomment the following line if using designed components   
  19.         //InitializeComponent();   
  20.     }  
  21.   
  22.     [WebMethod]  
  23.     public XmlElement GetEmployeeSearchResult(string EMP_Name)  
  24.     {  
  25.         using (SqlConnection con = new SqlConnection(@"Data Source=INDIA\MSSQLServer2k8; Initial Catalog=EmployeeManagement; Uid=sa; pwd=india;"))  
  26.         {  
  27.             using (SqlCommand cmd = new SqlCommand("SELECT * FROM EMPLOYEE WHERE Name like @EMP_Name+'%'", con))  
  28.             {  
  29.                 con.Open();  
  30.                 cmd.Parameters.AddWithValue("@EMP_Name", EMP_Name);  
  31.                 cmd.ExecuteNonQuery();  
  32.                 SqlDataAdapter da = new SqlDataAdapter(cmd);  
  33.                   
  34.                 DataSet ds = new DataSet();  
  35.                 da.Fill(ds);  
  36.                 con.Close();  
  37.                    
  38.                 XmlDataDocument xmldata = new XmlDataDocument(ds);  
  39.                 XmlElement xmlElement = xmldata.DocumentElement;  
  40.                 return xmlElement;  
  41.             }  
  42.         }  
  43.     }  
  44. }  
Now to check your Web Service. So run your application:

check your Web Service
                                                                           Image 5.

Now click on your Method name:

get employee result
                                                                        Image 6.

Run your application
                                                                              Image 7.

Now to consume this Web Service. So create a new ASP.NET application.

application
                                                                        Image 8.

Now right-click on your application in the Solution Explorer then select Add Web Reference.

add web reference
                              Image 9.

Type your Web Service URL and click GO. Then click on the Add Reference button:

Add Reference
                                                                     Image 10.

The following is the aspx:
  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></title>  
  7. </head>  
  8. <body>  
  9.     <form id="form1" runat="server">  
  10.     <div>  
  11.         <table style="border: solid 15px blue; width: 100%; vertical-align: central;">  
  12.             <tr>  
  13.                 <td style="padding-left: 20px; padding-top: 20px; padding-bottom: 20px; background-color: skyblue;  
  14.                     text-align: center; font-family: Verdana; font-size: 20pt; color: red;">  
  15.                     Web Services In ASP.NET C#  
  16.                 </td>  
  17.             </tr>  
  18.             <tr>  
  19.                 <td style="background-color: skyblue; text-align: center; font-family: Verdana; font-size: 14pt;  
  20.                     color: red;">  
  21.                     <b>Enter Employee Name:</b>  
  22.                     <asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>  
  23.                     <asp:Button ID="btnSearchEmployee" runat="server" Text="Search Employee" OnClick="btnSearchEmployee_Click" />  
  24.                 </td>  
  25.             </tr>  
  26.             <tr>  
  27.                 <td>  
  28.                     <table style="width: 80%; text-align: center; vertical-align: central;">  
  29.                         <tr>  
  30.                             <td style="text-align: left;">  
  31.                                 <asp:GridView ID="GridViewEmployee" runat="server" AutoGenerateColumns="False" Width="100%"  
  32.                                     BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px"  
  33.                                     CellPadding="4">  
  34.                                     <Columns>  
  35.                                         <asp:BoundField DataField="Name" HeaderText="Employee Name" HeaderStyle-HorizontalAlign="Left">  
  36.                                             <HeaderStyle HorizontalAlign="Left"></HeaderStyle>  
  37.                                         </asp:BoundField>  
  38.                                         <asp:BoundField DataField="Designation" HeaderText="Designation" HeaderStyle-HorizontalAlign="Left">  
  39.                                             <HeaderStyle HorizontalAlign="Left"></HeaderStyle>  
  40.                                         </asp:BoundField>  
  41.                                         <asp:BoundField DataField="City" HeaderText="City" HeaderStyle-HorizontalAlign="Left">  
  42.                                             <HeaderStyle HorizontalAlign="Left"></HeaderStyle>  
  43.                                         </asp:BoundField>  
  44.                                         <asp:BoundField DataField="State" HeaderText="State" HeaderStyle-HorizontalAlign="Left">  
  45.                                             <HeaderStyle HorizontalAlign="Left"></HeaderStyle>  
  46.                                         </asp:BoundField>  
  47.                                         <asp:BoundField DataField="Country" HeaderText="Country" HeaderStyle-HorizontalAlign="Left">  
  48.                                             <HeaderStyle HorizontalAlign="Left"></HeaderStyle>  
  49.                                         </asp:BoundField>  
  50.                                     </Columns>  
  51.                                     <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />  
  52.                                     <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />  
  53.                                     <PagerStyle ForeColor="#003399" HorizontalAlign="Left" BackColor="#99CCCC" />  
  54.                                     <RowStyle BackColor="White" ForeColor="#003399" />  
  55.                                     <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />  
  56.                                 </asp:GridView>  
  57.                             </td>  
  58.                         </tr>  
  59.                     </table>  
  60.                 </td>  
  61.             </tr>  
  62.         </table>  
  63.     </div>  
  64.     </form>  
  65. </body>  
  66. </html>  
The following is the aspx.cs:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.Xml;  
  9.   
  10. public partial class _Default : System.Web.UI.Page   
  11. {  
  12.     protected void Page_Load(object sender, EventArgs e)  
  13.     {  
  14.         if (!IsPostBack)  
  15.         {  
  16.             BindEmployee("");  
  17.         }  
  18.     }  
  19.   
  20.     protected void BindEmployee(string Emp_Name)  
  21.     {  
  22.         localhost.Service obj = new localhost.Service();  
  23.         DataSet ds = new DataSet();  
  24.         XmlElement exElement = obj.GetEmployeeSearchResult(Emp_Name);  
  25.         if (exElement != null)  
  26.         {  
  27.             XmlNodeReader nodeReader = new XmlNodeReader(exElement);  
  28.             ds.ReadXml(nodeReader, XmlReadMode.Auto);  
  29.             GridViewEmployee.DataSource = ds;  
  30.             GridViewEmployee.DataBind();  
  31.         }  
  32.         else  
  33.         {  
  34.             GridViewEmployee.DataSource = null;  
  35.             GridViewEmployee.DataBind();  
  36.         }  
  37.     }  
  38.     protected void btnSearchEmployee_Click(object sender, EventArgs e)  
  39.     {  
  40.         BindEmployee(txtEmpName.Text);  
  41.     }  
  42. }  
Now run your application:

run
                                                                        Image 11.

Now enter a name and click on Search.

Search
                                                                        Image 12.

enter employee name
                                                                           Image 13.

employee status
                                                                      Image 14.