This article gives an explanation about how to create web service in asp.net web forms and return the response in JSON and XML formate. Here I also explain how to retrieve data from the SQL server database using web service as well as also show you how you can retrieve data from the SQL server database.
Many developers/programmers those 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 service 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.
2) Create Sample Database and Create Table of Students and Insert some Dummy Records in Created Table For Demonstration.
3) Create Web Service to Return Data table with All the Information of All Students.
4) 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 press 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 Name of Your WebService and finally Click on Add button shown below.
NOTE: Make sure The file extension of your web service is (.asmx)
Step 5: Now, You have to do database connection with your application and write your connection string in your web.config file as I shown below.
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]
publicDataTable GetAllStudentsXML()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = newSqlConnection(constr))
{
using (SqlCommand cmd = newSqlCommand("SELECT * FROM Students with (NOLOCK)"))
{
cmd.Connection = con;
DataSet ds = newDataSet();
using (SqlDataAdapter sda = newSqlDataAdapter(cmd))
{
sda.Fill(ds, "Students");
}
return ds.Tables[0];
}
}
}
VB.NET
Return XML
<WebMethod()> _
PublicFunction GetAllStudentsXML() As DataTable
Dim constr AsString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con AsNew SqlConnection(constr)
Using cmd AsNew SqlCommand("SELECT * FROM Students with (NOLOCK)")
cmd.Connection = con
Dim ds AsNew DataSet()
Using sda AsNew SqlDataAdapter(cmd)
sda.Fill(ds, "Students")
EndUsingReturn ds.Tables(0)
EndUsingEndUsingEndFunction
Step 9: Now, Save created Web service and run the service by clicking F5 and invoke GetAllStudentsXML Method as shown below
Step 10: As a Response created web service will return all the following details of Students in XML format.
Step 11: To return 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.
Step 12: Now, you have to write following command in the Package Manager console.
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
[WebMethod]
publicstring GetAllStudentsJSON()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = newSqlConnection(constr))
{
using (SqlCommand cmd = newSqlCommand("SELECT * FROM Students with (NOLOCK)"))
{
cmd.Connection = con;
DataSet ds = newDataSet();
using (SqlDataAdapter sda = newSqlDataAdapter(cmd))
{
sda.Fill(ds, "Students");
}
returnJsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);
}
}
}
VB.NET
Return JSON
<WebMethod()> _
PublicFunction GetAllStudentsJSON() AsStringDim constr AsString = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con AsNew SqlConnection(constr)
Using cmd AsNew SqlCommand("SELECT * FROM Students with (NOLOCK)")
cmd.Connection = con
Dim ds AsNew DataSet()
Using sda AsNew SqlDataAdapter(cmd)
sda.Fill(ds, "Students")
EndUsingReturn JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented)
EndUsingEndUsingEndFunction
Step 15: Now, run the service and invoke GetAllStudentsJSON method.
Step 16: Your service will return the following result and now it will in JSON format.
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