What are Web services?

Web services are basically a XML or Json based information exchanged system used over internet within different programming platforms. Web service provide bridge between two platforms for example, if we want to connect our Android application with MS SQL database, asp.net asmx web service help us to do this. Web services exchange data over internet using SOAP (Simple Object Access Protocol).

This blog will explain you how to create Web service in asp.net using c# with Json response and performing CRUD (Create, Read, Update and Delete) operations using it.

Creating empty web site and MS SQL database

Step 1. Create an empty website from Visual Studio. (Open Visual Studio then select File-> New Web Site OR File-> New-> Web Site)

Step 2. Create database with single table with required columns ie. UserID, FullName, EmailAddress, Gender, Hobbies.

Creating Web services

Step 1. Right click on your website and select Add New Item.

Step 2. Select "Web Service" from the list. Give proper name to it and Add it to your web site by clicking Add button. Please remember to select Visual C# from left side of this window.

You can see two files has been added to your website 1. crudService.asmx and 2. crudService.cs inside App_Code folder. crudService.asmx file is basically used to run web services and crudService.cs has c# web methods inside it to perform connectivity tasks.

By default HelloWorld() web method is given.

[WebMethod]

public string HelloWorld() {

    return "Hello World";

}

What is Web Method [WebMethod]?

Web method [WebMethod] is an attribute used at top of methods written in web service. Basically this attribute shows that the method will be accessed over internet by users to perform task like database connectivity. If you do not used [WebMethod] attribute, it will become simple function and can’t be accessed over internet by users. 

Step 3. Create web methods [WebMethod] for operation you have to perform using web service. Here I have created web methods for Inert, Update, Delete and Select operations. You may add more methods as per your requirements. Below is my code.

crudService.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Data.SqlClient;

using System.Data;

using System.Web.Script.Services; /* Add this namespace */

using System.Web.Script.Serialization; /* Add this namespace */

  

/* // <summary> */

/* // Summary description for crudService */

/* // </summary> */

[WebService(Namespace = "http://tempuri.org/")]

[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 crudService : System.Web.Services.WebService

{

    /* Connection string */

    string strCon = "Data Source=DELL-PC;Initial Catalog=dbWebService;Integrated Security=True";

  

    public crudService()

    {

        /* Uncomment the following line if using designed components */

        /* InitializeComponent(); */

    }

  

    /* Insert Service */

    [WebMethod]

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)] /* Add this to get Response format in Json */

    public void fnRegistration(string FullName, string EmailAddress, string Gender, string Hobbies)

    {

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand("INSERT INTO tblCRUD(FullName,EmailAddress,Gender,Hobbies) VALUES('" + FullName + "','" + EmailAddress + "','" + Gender + "','" + Hobbies + "')", con);

        con.Open();

        int isInserted = cmd.ExecuteNonQuery();

        con.Close();

        List<Result> objListResult; /* Creating List of Result class */

        if (isInserted > 0)

        {

            objListResult = new List<Result>() { new Result() { msg = "Registration successfully..!!" } };

        }

        else

        {

            objListResult = new List<Result>() { new Result() { msg = "Error.. Please try again..!!" } };

        }

        Context.Response.Write(new JavaScriptSerializer().Serialize(objListResult));

    }

  

    /* Select Service */

    [WebMethod]

    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

    public void fnSelect()

    {

        SqlConnection con = new SqlConnection(strCon);

        SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM tblCRUD", con);

        DataTable dt = new DataTable("tblCRUD");

        da.Fill(dt);

        /* Creating List of Employee class */

        List<Employee> objListSocial = new List<Employee>(

                                                            (from DataRow row in dt.Rows

                                                               select new Employee()

                                                                 {

                                                                     FullName = row["FullName"].ToString()

                                                                    ,EmailAddress = row["EmailAddress"].ToString()

                                                                    ,Gender = row["Gender"].ToString()

                                                                    ,Hobbies = row["Hobbies"].ToString()

                                                                 }

                                                             ).ToList());

        Context.Response.Write(new JavaScriptSerializer().Serialize(objListSocial));

    }

  

    /* Update Service */

    [WebMethod]

    public void fnUpdate(int UserID, string FullName, string EmailAddress, string Gender, string Hobbies)

    {

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand("UPDATE tblCRUD SET FullName='" + FullName + "',EmailAddress='" + EmailAddress + "',Gender='" + Gender + "',Hobbies='" + Hobbies + "' WHERE UserID'" + UserID + "'", con);

        con.Open();

        int isUpdated = cmd.ExecuteNonQuery();

        con.Close();

        List<Result> objListResult; /* Creating List of Result class */

        if (isUpdated > 0)

        {

            objListResult = new List<Result>() { new Result() { msg = "Updated successfully..!!" } };

        }

        else

        {

            objListResult = new List<Result>() { new Result() { msg = "Error.. Please try again..!!" } };

        }

        Context.Response.Write(new JavaScriptSerializer().Serialize(objListResult));

    }

  

    /* Delete Service */

    [WebMethod]

    public void fnDelete(int UserID)

    {

        SqlConnection con = new SqlConnection(strCon);

        SqlCommand cmd = new SqlCommand("DELETE FROM tblCRUD WHERE UserID='" + UserID + "'", con);

        con.Open();

        int isDeleted = cmd.ExecuteNonQuery();

        con.Close();

        List<Result> objListResult; /* Creating List of Result class */

        if (isDeleted > 0)

        {

            objListResult = new List<Result>() { new Result() { msg = "Deleted successfully..!!" } };

        }

        else

        {

            objListResult = new List<Result>() { new Result() { msg = "Error.. Please try again..!!" } };

        }

        Context.Response.Write(new JavaScriptSerializer().Serialize(objListResult)); /* Converting List to Json and write it to response page */

    }

}

  

/* Create class as per requirement */

public class Employee

{

    public string FullName { get; set; }

    public string EmailAddress { get; set; }

    public string Gender { get; set; }

    public string Hobbies { get; set; }

}

public class Result

{

    public string msg { get; set; }

}

Understanding the code

1. Namespaces: Basically .asmx web service returns xml in response. So to convert that response to Json we have to use two namespaces and add it top of the page which I have already did in code.

using System.Web.Script.Services;

using System.Web.Script.Serialization;

2. ResponseFormat: To set web service response to Json add ResponseFormat attribute at top of every web methods. Like this,

[WebMethod]

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

3. Create class: Now we need to create class according to columns available in table. For example, I have FullName, EmailAddress, Gender and Hobbies columns in table, So I have created Employee class with all property and used it in fnSelect() webmethod. And result class is used to show message while inserting, updating and deleting.

public class Employee

{

    public string FullName { get; set; }

    public string EmailAddress { get; set; }

    public string Gender { get; set; }

    public string Hobbies { get; set; }

}

public class Result

{

    public string msg { get; set; }

}

4. Creating List of class: After creating classes, as we know we have multiple records in database to be fetched, we need to create List of particular class (Employee or Result) to convert our table to List.

List<Result> objListResult;

5. JavaScriptSerializer class: Last step is to use .Net JavaScriptSerializer class to convert our List to Json format. JavaScriptSerializer class has Serialize() function which convert list to Json. And to display that Json on web page use Context.Response.Write().

Context.Response.Write(new JavaScriptSerializer().Serialize(objListResult));

Please read out comments provided in code.

Run and Test web services

Step 1. To run our web service right click on crudService.asmx file from Solution Explorer where our web site is located. Select option View in Browser.

Step 2. Service will be run in browser window and it will look like,

All the [WebMethod] of you .cs page will be display here.

Step 3. Open service click on it.

Step 4. Click Invoke button to run it.

When you click on Invoke button, it will gives you output in Json format.

Output

Hope you will like this blog. Feel free to ask question. Thanks You… :)