How to create web services in ASP.NET?
In this article I am going to explain about how to create webservices in ASP.NET and how to implement webservice in .NET. And also in this webservice article I have return bulk of data as a Class.
Description :
I have store employee details in the "emp" table, through web service I am going to get employee name and his/here salary.Create SQLHelperClass
First we are going to create SQLHelperClass to read data from database
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
///
/// Summary description for ClsFun
///
public class ClsFun
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
public ClsFun()
{
//
// TODO: Add constructor logic here
//
}
public DataTable getdata(string qry)
{
sqlcon.Open();
sqlcmd = new SqlCommand(qry, sqlcon);
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
sqlcon.Close();
return dt;
}
public class empdet
{
public string eno = "";
public string empname = "";
public string sal = "";
public bool validuser = false;
}
public empdet ChkvalidUser(string id)
{
string query;
empdet s = new empdet();
query = "select * from emp where eno='" + id + "'";
dt = getdata(query);
if (dt.Rows.Count > 0)
{
s.eno = dt.Rows[0][0].ToString();
s.empname = dt.Rows[0][1].ToString();
s.sal = dt.Rows[0][2].ToString();
s.validuser = true;
}
else
{
s.validuser = true;
}
return s;
}
}Create Webservice WebService.asmx
webservice with SQL Helper class to get data from the database table
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Services;
using System.Web.Services.Protocols;
///
/// Summary description for WebService
///
[WebService(Namespace = "http://localhost:2323/04WsExample/WebService.asmx")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class EmployeeDetails : System.Web.Services.WebService
{
public EmployeeDetails()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
//[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(Namespace = "http://localhost:2323/04WsExample/WebService.asmx")]
//Create class to return more than one values
public class empResponse
{
public string eno;
public string empname;
public string sal;
}
[System.CodeDom.Compiler.GeneratedCode("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
//[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(Namespace = "http://localhost:2323/04WsExample/WebService.asmx")]
public class emp
{
private string id;
private string val;
public string id1
{
get
{
return this.id;
}
set
{
this.id = value;
}
}
public string val1
{
get
{
return this.val;
}
set
{
this.val = value;
}
}
}
[WebMethod(BufferResponse = true, Description = "Get Employee Details")]
[ScriptMethod(ResponseFormat = ResponseFormat.Xml, XmlSerializeString = true)]
//Get employee details using employee numeber
public empResponse GetEmployeeDetails(string eno)
{
empResponse resp = new empResponse();
//Create instance for sqlheleper class
ClsFun obj = new ClsFun();
//Create instance for employee details return values
ClsFun.empdet obj1 = new ClsFun.empdet();
//Check valid user or not match with database value
obj1 = obj.ChkvalidUser(eno);
if (obj1.validuser == true)
{
resp.eno = obj1.eno;
resp.empname = obj1.empname;
resp.sal = obj1.sal;
}
//return over all response value instance
return resp;
}
}
Now run the Webservice to test it working fine
Adding Web service as Web Reference to Project
Now add the web reference to your project
Right click on the project name in the solution explorer and choose Add Web reference and paste the above image web service url
http://localhost:2323/04WsExample/WebService.asmx
Note: Here I have deployed webservices in local so I use localhost url after you hosted in the domain use that url.Access from webpage
After you add reference to your project you directly access web services return data using create instance of web service class. Refer below code sample how to access web services from ASP.NET page.Client Side
I have collect employee no from user to get result using web service and bind it in the label.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
Enter eno<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" Style="height: 26px" />
<br />
<br />
<br />
<asp:Label ID="lblResult" runat="server"></asp:Label>
</div>
</form>
</body>
</html>Server Side
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using localhost;
public partial class _Default : System.Web.UI.Page
{
localhost.EmployeeDetails obj = new localhost.EmployeeDetails();
protected void Page_Load(object sender, EventArgs e)
{
//Make sure you add web reference before
lblResult.Text = "";
}
protected void Button1_Click(object sender, EventArgs e)
{
//Declare isntance for web service class
empResponse obj1 = new empResponse();
//Get employee all details using eno textbox
obj1 = obj.GetEmployeeDetails(TextBox1.Text);
//Write it all details in web page
lblResult.Text = "Employee No:" + obj1.eno ;
lblResult.Text = lblResult.Text + "
Employee Name:" + obj1.empname;
lblResult.Text = lblResult.Text + "
Employee Salary:" + obj1.sal;
}
}Output :
Source code:
Client Side: ASP.NET
Code Behind: C#Conclusion
I hope this code snippet is helping you to know about how to create web service and how to implement in ASP.NET.
Follow below link which explains web service creation step by step.
http://sharepointcafe.net/tutorial/web-services-in-asp-net