How to Create Web Service in ASP.NET Web Forms With Example

watch_later 3/11/2019

This article gives an explanation about how to create web service in asp.net web forms and return the response in JSON and XML format. Here I also explain how to retrieve data from the SQL server database using a web service as well as also show you how you can retrieve data from the SQL server database.


How to Create Web Service in ASP.NET Web Forms With Example

Many developers/programmers who work with data-driven web applications will have at least 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 services 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

  1. Create ASP.Net Web Form Application.
  2. Create a Sample Database Create a Table of Students and Insert some Dummy Records in Created Table For Demonstration.
  3. Create a Web Service to Return a Data table with All the Information of All Students.
  4. The 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.


Create-asp-dot-net-empty-website

Step 3: Now, You have to add Web Service to the project, and for that, you have to press right-click on your project name from Solution Explorer and Click on ADD >> ADD NEW ITEM.


add-new-items

Step 4: Again one popup window will appear on your screen where you have to select "Web Service (ASMX)" give the Name of Your WebService and finally Click on Add button shown below.


create-codingvila-web-service

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 shown below.

  <connectionStrings>
    <add name="constr" connectionString="Data Source=DESKTOP-P1PHIU6\SQLEXPRESS;Initial Catalog=DB_Codingvila;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>

Step 6: Then after, You have to open the cs file of your web service (Codingvila.asmx.cs) and you need to add the following required Namespaces.

using System.Configuration;
using System.Data;
using Newtonsoft.Json;
using System.Data.SqlClient;

Step 7: Now, you should create a simple table for Students with some dummy data in the SQL server.

CREATE TABLE [dbo].[Students]
(
	[StudentId] INT NOT NULL PRIMARY KEY IDENTITY, 
    [RollNo] INT NULL, 
    [FirstName] NVARCHAR(20) NULL, 
    [LastName] NVARCHAR(20) NULL, 
    [Branch] NVARCHAR(20) NULL, 
    [College] NVARCHAR(50) NULL
)
INSERT INTO Students (RollNo,FirstName,LastName,Branch,College) VALUES 
(1001,'Nikunj','Satasiya','CSE','RK University'),
(1002,'Hiren','Dobariya','CSE','RK University'),
(1003,'Vishal','Sabhaya','CSE','RK University'),
(1004,'Sruti','Patel','IT','RK University'),
(1005,'Priya','Patel','EC','RK University'),
(1006,'Vivek','Ghadiya','CSE','RK University')

Step 8: Then after, 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

[WebMethod]
    public DataTable GetAllStudentsXML()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Students with (NOLOCK)"))
            {
                cmd.Connection = con;
                DataSet ds = new DataSet();
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    sda.Fill(ds, "Students");
                }
                return ds.Tables[0];
            }
        }
    }

VB.NET

Return XML

<WebMethod()> _
    Public Function GetAllStudentsXML() As DataTable
 
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("SELECT * FROM Students with (NOLOCK)")
                cmd.Connection = con
                Dim ds As New DataSet()
                Using sda As New SqlDataAdapter(cmd)
 
                    sda.Fill(ds, "Students")
                End Using
                Return ds.Tables(0)
            End Using
        End Using
    End Function

Step 9: Now, Save created Web service and run the service by clicking F5 and invoke GetAllStudentsXML Method as shown below


web-service-return-result-in-xml-1

Step 10: As a Response created web service will return all the following details of Students in XML format.

web-service-return-result-in-xml-2

Step 11: To return the Result as JSON, if you didn't have a reference of 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 Package Manager console as shown in the screen below.

Install-Package Newtonsoft-dot-Json

Step 12: Now, you have to write the following command in the Package Manager console.

PM> Install-Package Newtonsoft.Json

Install-Package Newtonsoft-Json

This command will add the reference of Newtonsoft.Json to 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.

Install-Package Newtonsoft-dot-Json

Step 14: Now, we will create another method to retrieve the details of students in JSON format.

C#

Return JSON

[WebMethod]
    public string GetAllStudentsJSON()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Students with (NOLOCK)"))
            {
                cmd.Connection = con;
                DataSet ds = new DataSet();
                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    sda.Fill(ds, "Students");
                }
                return JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);
            }
        }
    }

VB.NET

Return JSON

<WebMethod()> _
 
    Public Function GetAllStudentsJSON() As String
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("SELECT * FROM Students with (NOLOCK)")
                cmd.Connection = con
                Dim ds As New DataSet()
                Using sda As New SqlDataAdapter(cmd)
                    sda.Fill(ds, "Students")
                End Using
                Return JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented)
            End Using
        End Using
    End Function

Step 15: Now, run the service and invoke the GetAllStudentsJSON method.


web-service-return-result-in-Json-1

Step 16: Your service will return the following result and now it will be in JSON format.

web-service-return-result-in-Json-2

Step 17: done.

Codingvila provides articles and blogs on web and software development for beginners as well as free Academic projects for final year students in Asp.Net, MVC, C#, Vb.Net, SQL Server, Angular Js, Android, PHP, Java, Python, Desktop Software Application and etc.

Thank you for your valuable time, to read this article, If you like this article, please share this article and post your valuable comments.

Once, you post your comment, we will review your posted comment and publish it. It may take a time around 24 business working hours.

Sometimes I not able to give detailed level explanation for your questions or comments, if you want detailed explanation, your can mansion your contact email id along with your question or you can do select given checkbox "Notify me" the time of write comment. So we can drop mail to you.

If you have any questions regarding this article/blog you can contact us on info.codingvila@gmail.com

sentiment_satisfied Emoticon