How to Create a Web Services In ASP.net with C# - Example

How to Create a Web Services In ASP.net with C# for passing Bunchrecords to From One Web Application to other Web Application - Example

In this article we talk about web services. First well start with What is Web Services ? and How we can use web services in  our web application ? Then we will see step by step Implementation of Web service in Asp.net Application.

What is Web Service?

Web Service is an application that is used to interact with other applications over the internet. Web services is a one type of mechanism that ASP.NET framework provides to interact with other web applications. Using Web Services you can call the remote objects and methods.
Web Services use XML format  for communication over internet that make Web Services Language Independent, Protocol Independent and Platform Independent.

This xml formatted messages are sent and received via HTTP, so that you can call methods on any server without being blocked by firewall. this is possible when client and server agree to a contract, Which is defined using WSDL and an XSL Schema Definition (XSD). Now the Question is

What is WSDL?

WSDL means Web Service Description Language Tool. This tool can take a WSDL file and generate a corresponding proxy class that you can use to invoke the web service. Alternate of generating Proxy class is you can use "web reference". Web Reference used to point the web service over internet.

How to implement Web Services ?

Here is the Scenario that I will create web service in that service i will create one method named "GetUserDetails(string UserName)", this method will be called in Other Web Application and get the records of User name which i had passed.

Step1:-   First Create or Open the web application in which you want to create Web Application. Now right click on your application and choose "Add New" option and add the "Web Services" and give the proper name  to that web service the extension of web service is ".asmx". Initially your web service  is like below.


Step 2:- Now we will write the method in Web service File this method will be called by other web application. means we will write the logic of web service here is my the code logic. add this code in web service.


[WebMethod] 
public XmlElement GetUserDetails(string userName)
        {
            SqlConnection con = new SqlConnection("Data Source=SQLDB;Initial Catalog=Demo;Persist Security Info=True;User ID=Demoh;Password=Demo1@");
            con.Open();
            SqlCommand cmd = new SqlCommand("select id, fname, category from aby_temp", con);
           cmd.ExecuteNonQuery();
           SqlDataAdapter da = new SqlDataAdapter(cmd);
            // Create an instance of DataSet.
            DataSet ds = new DataSet();
            da.Fill(ds);
            con.Close();
            // Return the DataSet as an XmlElement.
            XmlDataDocument xmldata = new XmlDataDocument(ds);
            XmlElement xmlElement = xmldata.DocumentElement;
            return xmlElement;
        }


     
In the above method I am selecting bunch of records and return this records in XML format.
for this code you have to add following namespaces in you Code File.

using System.Xml;
using System.Data;
using System.Data.SqlClient;

Step-3 :- Compile this application successfully and publish this web application locally. If you don't know how to publish then  go to my earlier post How to publish web site or web application locally.

Before going to next step make sure your application is successfully published on locally published

Step-4:- copy the path of the web service of the web application which you had published in above step. you can get this path from IIS Manager.open the IIS Manager and open your published web application in content view of this application you got your web service file now right click on web service file and choose "Browse"  you can refer this process in below image Here in my case I had published "BloggerCodeTesterPublished"   application.



Step-5 :-Add Web Reference of Published Web service in your Web Application for that open or create web application from where you want to access the web service.
  1. Now right click on web application in solution explorer an choose "Add Service Reference.." option.
  2. Now you get "Add service window" in this window click the "Advance" button at Left-bottom part of window.
  3. New window named "Service reference Settings" will be opened click "Add Web References" Button at Left-Bottom.
  4. "Add Web Reference" window will be opened in URL Field enter the URL of Web Service which you have published and press "Enter" key In Below part you should  get the name of method that you had declared in your published  web service.
  5. Provide "Web Reference Name:" by default it is local host Click "Add Reference " now you get one new folder in your solution explorer named " App_WebReferences"  after this  almost 80% work is done.


Step-6:- Now we will write a code to access this method. write below code where you want to access the method here in my case the method name is "GetUserDetails".  I had access this method by creating object of " localhost.WebService1"  and store the return value object in XmlElement and bind that data in Grid view.

Code in C#:-


using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindUserDetails("Abhay");
        }
    }
    protected void BindUserDetails(string userName)
    {
        localhost.WebService1 objUserDetails = new localhost.WebService1();
        DataSet dsresult = new DataSet();
        XmlElement exelement = objUserDetails.GetUserDetails(userName);
        if (exelement != null)
        {
            XmlNodeReader nodereader = new XmlNodeReader(exelement);
            dsresult.ReadXml(nodereader, XmlReadMode.Auto);
            gvUserDetails.DataSource = dsresult;
            gvUserDetails.DataBind();
        }
        else
        {
            gvUserDetails.DataSource = null;
            gvUserDetails.DataBind();
        }
    }
 }

Aspx Page code:-


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
</head> <body>
 <form id="form1" runat="server"> <div>

 <asp:GridView ID="gvUserDetails" runat="server"></asp:GridView>

 </div> </form> </body> </html>


Post a Comment