Here we are going to learn how to create a web services in ASP.NET which will return data as XML and JSON.
Step 1: Create new project and select ASP.NET web Application.
Step 2: Select
Empty template and click
OK.
Step 3: Now add
Web Service in project and give it name
webservice1.asmx,
Step 4: Make sure you add the connection string in your web.config file as in the following screenshot,
Step 5: Now add the references System.data, System.Data.SqlClient and System.configuration,
Step 6: Create Employee table and run the following script in your SQL query editor,
- /****** Object: Table [dbo].[Employee] Script Date: 09-12-2015 23:40:32 ******/
- SET
- ANSI_NULLS ON GO
- SET
- QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[Employee](
- [EmpId] [int] IDENTITY(1, 1) NOT NULL,
- [EmpFirstName] [nvarchar](50) NULL,
- [EmpLastName] [nvarchar](50) NULL,
- [DeptId] [int] NULL,
- CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED ([EmpId] ASC) WITH (
- PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
- IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
- ALLOW_PAGE_LOCKS = ON
- ) ON [PRIMARY]
- ) ON [PRIMARY] GO
Now add the following method in your webservice1.asmx.cs file,
- [WebMethod]
- public DataSet getEmp()
- {
- string sql = "SELECT [EmpId],[EmpFirstName],[EmpLastName],[DeptId] FROM Employee";
- SqlDataAdapter da = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["Connection"].ToString());
- DataSet ds = new DataSet();
- da.Fill(ds);
- return ds;
- }
Write a SQL query, create a SqlDataAdapter object and pass the SQL query and connection string.
Step 7: Save and run the services by clicking F5 and invoking getEmp method as in the following,
Step 8 : Click on
Invoke.
Step 9: It will return all the employees details in XML format.
Step 10 : Now for JSON return please add newtonsoft.json from the NuGet Manager. Go to Tools, then NuGet Package Manager and click on Package Manager console.
Step 11: Write PM> Install-Package Newtonsoft.Json. It will add the reference Newtonsoft.Json in our project.
Step 12: It will display Success message as per the following screen, once you install the package.
Step 13: Now add the reference Newtonsoft.Json in your code.
Step 14: Create the method 'getEmployee' same as above method 'getEmp'. The only difference here is we use jsonConvert.SerializateIbject to serialize the data.
- [WebMethod]
- public string getEmployee()
- {
- string sql = "SELECT [EmpId],[EmpFirstName],[EmpLastName],[DeptId] FROM Employee";
- SqlDataAdapter da = new SqlDataAdapter(sql, ConfigurationManager.ConnectionStrings["Connection"].ToString());
- DataSet ds = new DataSet();
- da.Fill(ds);
- return JsonConvert.SerializeObject(ds, Newtonsoft.Json.Formatting.Indented);
- }
Step 15: Now run the service and invoke
getEmployee method.
Step 16: It will return the same data but in JSON format.
Thanks for reading the article. Hope you like it.