How To Create Web Service In ASP.NET Web Forms With Example

Introduction

 
This article gives an explanation about how to create web service in asp.net web forms and return the response in JSON and XML formats. Here I also explain how to retrieve data from the SQL server database using web service, as well as show you how you can retrieve data from the SQL server database.
 
Many developers/programmers who work with data-driven web applications will at least have heard talk about the web service. Even if any developers/programmers know on a basic level what web services do, they are not always certain when to use web service and how to write the code to use web services. So, in this article, I am going to show you how to create web services in ASP.NET and return data in JSON and XML format.
 
Requirement
  • Create ASP.Net Web Form Application.
  • Create Sample Database and Create Table of Students and Insert some Dummy Records in Created Table For Demonstration.
  • Create Web Service to Return Data table with All the Information of All Students.
  • Response Message should be XML or JSON. 

Implementation

 
Step 1
 
Open Your Visual Studio 2013 Or Higher Version.
 
Step 2
 
Go To File Menu and Create New Project and then Select "ASP.NET Empty Web Site", and Set project path location and Click on Ok. Same as shown in the screen below.
 
 
Step 3
 
Now, you have to add Web Service in the project and for that, you have to  right-click on your project name from Solution Explorer and Click on ADD >> ADD NEW ITEM.
 
 
Step 4
 
Again one popup window will appear on your screen where you have to select "Web Service (ASMX)" and give the Name of Your WebService and finally Click on the Add button shown below.
 
 
NOTE
Make sure the file extension of your web service is (.asmx)
 
Step 5
 
Now, you have to do a database connection with your application and write your connection string in your web. config file as I shown below.
  1. <connectionStrings>  
  2.   <add name="constr" connectionString="Data Source=DESKTOP-P1PHIU6\SQLEXPRESS;Initial Catalog=DB_Codingvila;Integrated Security=True" providerName="System.Data.SqlClient"/>  
  3. </connectionStrings>  
Step 6
 
Then you have to open cs file of your web service (Codingvila.asmx.cs) and you need to add the following required Namespaces.
  1. using System.Configuration;  
  2. using System.Data;  
  3. using Newtonsoft.Json;  
  4. using System.Data.SqlClient;  
Step 7
 
Now, you should create a simple table for Students with some dummy data in SQL server.
  1. CREATE TABLE [dbo].[Students]  
  2. (  
  3.     [StudentId] INT NOT NULL PRIMARY KEY IDENTITY,   
  4.     [RollNo] INT NULL,   
  5.     [FirstName] NVARCHAR(20) NULL,   
  6.     [LastName] NVARCHAR(20) NULL,   
  7.     [Branch] NVARCHAR(20) NULL,   
  8.     [College] NVARCHAR(50) NULL  
  9. )  
  1. INSERT INTO Students (RollNo,FirstName,LastName,Branch,College) VALUES   
  2. (1001,'Nikunj','Satasiya','CSE','RK University'),  
  3. (1002,'Hiren','Dobariya','CSE','RK University'),  
  4. (1003,'Vishal','Sabhaya','CSE','RK University'),  
  5. (1004,'Sruti','Patel','IT','RK University'),  
  6. (1005,'Priya','Patel','EC','RK University'),  
  7. (1006,'Vivek','Ghadiya','CSE','RK University')  
Step 8
 
Then you need to add the following method in your created web service (Codingvila.asmx.cs) file to retrieve all records from the student's table.
 
C#
 
Return XML
  1. [WebMethod]  
  2.     public DataTable GetAllStudentsXML()  
  3.     {  
  4.         string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
  5.         using (SqlConnection con = new SqlConnection(constr))  
  6.         {  
  7.             using (SqlCommand cmd = new SqlCommand("SELECT * FROM Students with (NOLOCK)"))  
  8.             {  
  9.                 cmd.Connection = con;  
  10.                 DataSet ds = new DataSet();  
  11.                 using (SqlDataAdapter sda = new SqlDataAdapter(cmd))  
  12.                 {  
  13.                     sda.Fill(ds, "Students");  
  14.                 }  
  15.                 return ds.Tables[0];  
  16.             }  
  17.         }  
  18.     }  
VB.NET
 
Return XML
  1. <WebMethod()> _    
  2.     Public Function GetAllStudentsXML() As DataTable    
  3.      
  4.         Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString    
  5.         Using con As New SqlConnection(constr)    
  6.             Using cmd As New SqlCommand("SELECT * FROM Students with (NOLOCK)")    
  7.                 cmd.Connection = con    
  8.                 Dim ds As New DataSet()    
  9.                 Using sda As New SqlDataAdapter(cmd)    
  10.      
  11.                     sda.Fill(ds, "Students")    
  12.                 End Using    
  13.                 Return ds.Tables(0)    
  14.             End Using    
  15.         End Using    
  16.     End Function     
Step 9
 
Now, save the created Web service and run the service by clicking F5 and invoking the GetAllStudentsXML method as shown below
 
 
Step 10
 
As a response the created web service will return all the following details of Students in XML format.
 
 
Step 11
 
To return the Result as JSON, if you didn't have a reference for newtonsoft.json then you need to add newtonsoft.json from the NuGet Manager. and for that Go to Tools >> NuGet Package Manager and click on the Package Manager console as shown on the screen below.
 
 
Step 12
 
Now, you have to write the following command in the Package Manager console.
  1. PM> Install-Package Newtonsoft.Json  
 
This command will add the reference of Newtonsoft.Json in your project.
 
Step 13
 
After successful installation of the package you have to add the reference Newtonsoft.Json in your created web service (Codingvila.asmx.cs) file.
 
 
Step 14
 
Now, we will create another method to retrieve details of students in JSON format.
 
C#
 
Return JSON
  1. [WebMethod]  
  2.     public string GetAllStudentsJSON()  
  3.     {  
  4.         string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;  
  5.         using (SqlConnection con = new SqlConnection(constr))  
  6.         {  
  7.             using (SqlCommand cmd = new SqlCommand("SELECT * FROM Students with (NOLOCK)"))  
  8.             {  
  9.                 cmd.Connection = con;  
  10.                 DataSet ds = new DataSet();  
  11.                 using (SqlDataAdapter sda = new SqlDataAdapter(cmd))  
  12.                 {  
  13.                     sda.Fill(ds, "Students");  
  14.                 }  
  15.                 return JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);  
  16.             }  
  17.         }  
  18.     }  
VB.NET
 
Return JSON
  1. <WebMethod()> _  
  2.    
  3.     Public Function GetAllStudentsJSON() As String  
  4.         Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString  
  5.         Using con As New SqlConnection(constr)  
  6.             Using cmd As New SqlCommand("SELECT * FROM Students with (NOLOCK)")  
  7.                 cmd.Connection = con  
  8.                 Dim ds As New DataSet()  
  9.                 Using sda As New SqlDataAdapter(cmd)  
  10.                     sda.Fill(ds, "Students")  
  11.                 End Using  
  12.                 Return JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented)  
  13.             End Using  
  14.         End Using  
  15.     End Function  
Step 15
 
Now, run the service and invoke the GetAllStudentsJSON method.
 
 
Step 16
 
Your service will return the following result and now it will be in JSON format.
 
 
Step 17
 
Done.
 

Summary

 
In this article, we learned how to create a web service in asp.net web forms and return the response in JSON and XML formats.
 
To download sample source code, please visit the given reference link and download the source code from there as I am not able to attach it here due to file size limitation. 
 


Similar Articles
Codingvila
Codingvila is an educational website, developed to help tech specialists/beginners.