ASP.Net Web API with Fiddler and Postman

Description: In this article, we will learn about the concept of ASP.NET Web API using Visual Studio 2015. Also, we will learn to test Web API using Fiddler and Postman Clients.

Agenda:

  • Creating the very basic WebApi project in Visual Studio
  • Create methods to perform CRUD (Create, Read, Update and Delete) operations with WebApi Controller using ADO.NET Entity Framework 6.1.3
  • Learn the way to make your WebApi return data in specific formats like JSON, XML etc.
  • Downloading and installing Fiddler tool and testing the WebApi with it
  • Downloading and installing Postman tool and testing the WebApi with it

ASP.NET Web API is a framework that allow us to build HTTP services over the top of .NET Framework. It is so flexible that it can reach a broad range of clients, including browsers and portable devices. It’s main feature, which makes it unique, is that it is RESTful (Representational State Transfer) i.e. all that data is passed over HTTP and not on SOAP like that of WCF Services.

Unlike SOAP, a WebApi works on pre-defined standards i.e. it has pre-defined verbs, known as HTTP verbs, to work. These verbs are mentioned below:

  1. GET – It is used to fetch the data
  2. PUT – It is used to update the data
  3. POST – It is used to create the data
  4. DELETE – It is used to delete the data

Note: ASP.NET WebApi works on the MVC (Model-View-Controller) architectural pattern, so MVC is a pre-requisite.

Creating a WebApi Project in Visual Studio:

Step 1: Run Visual studio on your machine and click on New Project.

Step 2: The below dialog box appears, click on Web under Visual C# tab –> ASP.NET Web Application –> Give the name of the project –> OK.

Step 3: Select the WebApi option and click on OK.

Step 4: Create the Database and Insert some sample data using the following SQL script.

CREATE TABLE [dbo].[Product] (
    [Id]       INT           IDENTITY (1, 1) NOT NULL,
    [Name]     VARCHAR (100) NOT NULL,
    [Price]    INT           NOT NULL,
    [Category] VARCHAR (100) NOT NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
)
 
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (1, N'Mobile', 500, N'Electronics')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (2, N'Tablet', 700, N'Electronics')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (3, N'Mouse', 200, N'Electronics')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (4, N'Keyboard', 340, N'Electronics')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (5, N'Speakers', 5000, N'Electronics')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (6, N'T-Shirts', 100, N'Wearables')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (7, N'Pants', 120, N'Wearables')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (8, N'Jeans', 540, N'Wearables')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (9, N'Chips', 50, N'Eatables')
INSERT INTO [dbo].[Product] ([Id], [Name], [Price], [Category]) VALUES (10, N'Coke', 30, N'Eatables')

The final table will be like below.

Now we need to do all the CRUD operations on the above table and data.

Step 5: Create a Class Library project that connects to database and provide us with the required classes and properties using ADO.NET Entity framework.

Step 6: After clicking on Finish Button, you will see the below EDMX file showing the data-entity relationship as defined in database.

Now, we are done with the connectivity to Database.

Step 7: Now, we need to add the reference of the above created project in our Web Api project, so follow the below steps.

Step 8: Now we need to create a new ProductsController.cs file in the Controllers folder of WebApi Project. This file will contain the methods that corresponds to HTTP verbs that we discussed in the very begining of this tutorial.

Step 9: Add the following code to the ProductsController.cs.

public ProductEntities Entities = new ProductEntities();
 
        public HttpResponseMessage Get()
        {
            try
            {
                return Request.CreateResponse(HttpStatusCode.Found, Entities.Products.ToList());
            }
            catch (Exception)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");
            }
        }
 
        public HttpResponseMessage Get(int id)
        {
            try
            {
                return Request.CreateResponse(HttpStatusCode.Found, Entities.Products.SingleOrDefault(p => p.Id == id));
            }
            catch (Exception)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");
            }
        }
 
        public HttpResponseMessage Post([FromBody] Product product)
        {
            try
            {
                Entities.Products.Add(product);
                Entities.SaveChanges();
                var response = Request.CreateResponse(HttpStatusCode.Created, product);
                response.Headers.Location = Request.RequestUri;
 
                return response;
            }
            catch (Exception)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Data not inserted");
            }
        }
 
        public HttpResponseMessage Delete(int id)
        {
            try
            {
                var product = Entities.Products.SingleOrDefault(p => p.Id == id);
                if (product == null)
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not found to delete");
                Entities.Products.Remove(product);
                Entities.SaveChanges();
 
                return Request.CreateResponse(HttpStatusCode.OK, "Product Deleted Successfully");
            }
            catch (Exception)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not deleted");
            }
        }
 
        public HttpResponseMessage Put(int id, [FromBody] Product product)
        {
            try
            {
                var entity = Entities.Products.SingleOrDefault(p => p.Id == id);
                if (entity == null)
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Product not found ");
 
                entity.Category = product.Category;
                entity.Name = product.Name;
                entity.Price = product.Price;
                Entities.SaveChanges();
 
                return Request.CreateResponse(HttpStatusCode.OK, "Product Updated Successfully");
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }

Step 10: Go to App_Start folder of the root directory and open WebApiConfig.cs file and add the following code of lines.

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.Formatters.Remove(config.Formatters.XmlFormatter);

The above two lines makes the API, only JSON supported. So, by default, now our API will support only JSON Media type format.

Now, our API is ready. Just add the below connection string to the API’s web.config file.

<add name="ProductEntities"
connectionString="metadata=res://*/ProductsModel.csdl|res://*/ProductsModel.ssdl|res://*/ProductsModel.msl;
provider=System.Data.SqlClient;provider connection string="
data source=(local);initial catalog=DemoDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework""
providerName="System.Data.EntityClient" />

Press Ctrl + F5 and navigate to http://localhost:26317/api/products. You will see the details of product table in JSON format as below.

Now, as per the Agenda of this article, we will install Fiddler tool and Postman tool to test the API functionality.

Using Fiddler to test Web Api

Step 1: Download the fiddler from the below url and as shown in the screenshot.

Install the downloaded exe file and run it.

Step 2: First we will check the GET functionality. So, follow the steps shown in screenshot below and you will get the result in JSON format.

fiddlerdel1

Step 2: Now we will test POST (Insert) functionality.

Now the data is inserted on 12th row.

Step 3: Now we will update the data on 12th Id using the PUT functionality.

Now, the data is updated successfully.

Step 4: Now we will DELETE the 12th record.

But, using Fiddler to just test the Web Api functionality looks complicated, so instead of using Fiddler, we can use Postman (Google Chrome Extension).

Using Postman to test Web Api

Step 1: Install Postman App in Google Chrome browser as shown below.

Step 2: Run Postman app from the Apps option in Google chrome browser. So, now testing the GET Functionality.

Step 3: Testing the POST functionality.

So, the record is inserted at 13th row.

Step 4: Testing the PUT functionality.

So, data updated in Database.

Step 5: Finally test the Delete functionality.

Conclusion: Personally, I feel using Postman to test Web Api’s and WCF services. We can also use fiddler, but if the API is too complex, so I recommend to use Fiddler as it gives more flexibility to test the services.

Hope you liked the above tutorial. If so, do comment with your compliments and queries. I will try to reply ASAP.

Advertisements

Display data in ASP.NET using jQuery DataTables Plugin

Description – This tutorial gives a walkthrough of jQuery Datatables plugin to display the data stored in Database using ASP.Net web Services.

Below is the screenshot of the final output that we want to achieve at the end of this tutorial.

7

So, the above is a table that allows almost all functionalities that a user wants to view data, filter data, sort data etc. This is achieved by using jQuery datatables plugin.

Step 1: First we need to create some sample data in our SQL database. Below is the script that I have used to generate test data. You can use the below script or create your own data.

Create Database Test
 
Use Test
 
Create Table Students 
(
iD int primary key not null identity(1,1),
firstName nvarchar(MAX) not null,
lastName nvarchar(MAX) not null,
feesPaid int not null,
gender nvarchar(MAX) not null,
emailId nvarchar(MAX) not null,
telephoneNumber nvarchar(MAX) not null,
dateOfBirth date not null,
isActive bit not null,
creationDate datetime not null,
lastModifiedDate datetime not null
)
GO
 
INSERT INTO Students VALUES ('Ankit','Bansal',45000, 'Male', 'ankit@a.com','2564210000','20/May/1993',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Raj','Kumar',25000, 'Male', 'raj@r.com','25400123000','20/June/1993',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Badrish','Joshi',32000, 'Male', 'badrish@b.com','10213330120','25/May/1989',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Rajesh','Negi',56000, 'Male', 'rajesh@r.com','89546332021','18/July/1978',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Rajkishor','Singh',46000, 'Male', 'rajkishor@r.com','8546795555','11/August/1985',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Neha','Arora',98652, 'Female', 'neha@n.com','96542231000','02/May/1996',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Sanjay','Sharma',65421, 'Male', 'sanjay@s.com','99876653222','25/Jan/1998',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Glenn','Block',65210, 'Male', 'glenn@g.com','54210000021','27/Feb/1990',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Sara','Silver',78900, 'Female', 'sara@s.com','89778930099','10/Sep/1989',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Lucy','Bane',23444, 'Female', 'lucy@l.com','2564210000','20/May/1993',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Suresh','Goswami',65321, 'Male', 'suresh@s.com','9876576489','21/Nov/1981',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Dinesh','Gola',76544, 'Male', 'dinesh@d.com','9899785412','15/March/1984',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Shivansh','Manaktala',87555, 'Male', 'shivansh@s.com','6755439000','17/Oct/1994',1,GETDATE(),GETDATE())
GO
INSERT INTO Students VALUES ('Mahendra','Dhoni',65789, 'Male', 'mahendra@m.com','9856421003','15/March/1987',1,GETDATE(),GETDATE())
GO
 
Create Procedure getStudents
As 
Begin
   Select * from Students Where isActive=1
End

Step 2: Download jQuery Datatables plugin core files from its website. Go to http://datatables.net/download/index and follow the below steps.

Step 3: Create an Empty ASP.NET web application project and add the above downloaded files to it.

Step 4: Add a class file named students.cs with some auto-implemented properties. You can copy and paste the below code if you are using my SQL script.

using System;
 
namespace dataTablesPlugin
{
    class Students
    {
        public int iD { getset; }
        public string firstName { getset; }
        public string lastName { getset; }
        public int feesPaid { getset; }
        public string gender { getset; }
        public string emailId { getset; }
        public string telephoneNumber { getset; }
        public DateTime dateOfBirth { getset; }
    }
}

Explanation: We have created properties in the class file with the same name as that of our database table columns. This helps us to retrieve data from sql database.

Step 5: Create a connection string in the Web.config file.

<connectionStrings>
    <add connectionString="Data Source=.;Initial Catalog=Test;Integrated Security=True" name="dbcs" providerName="System.Data.SqlClient"/>
  </connectionStrings>

The above string is used to connect to Database using .net sql client.

Step 6: Add a ASP.NET web service named StudentService.asmx and add the following code to it.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
 
namespace dataTablesPlugin
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class StudentService : System.Web.Services.WebService
    {
        [WebMethod]
        public void GetStudents()
        {
            var cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
            var students = new List<Students>();
            using (var con = new SqlConnection(cs))
            {
                var cmd = new SqlCommand("getStudents", con) {CommandType = CommandType.StoredProcedure};
                con.Open();
                var dr = cmd.ExecuteReader();
                while (dr.Read())
                {
                    var student = new Students
                    {
                        iD = Convert.ToInt32(dr[0].ToString()),
                        firstName = dr[1].ToString(),
                        lastName = dr[2].ToString(),
                        feesPaid = Convert.ToInt32(dr[3].ToString()),
                        gender = dr[4].ToString(),
                        emailId = dr[5].ToString(),
                        telephoneNumber = dr[6].ToString(),
                        dateOfBirth = Convert.ToDateTime(dr[7].ToString())
                    };
                    students.Add(student);
                }
            }
            var js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(students));
        }
    }
}

The above code is a simple ADO.NET code that create a list of Students and retrieve data from database stored procedure and read each property value from it and stores it in our class properties. At the last of this code, JavaScriptSerializer class is used to convert the received data in JSON format so that our Datatables plugin can consume that data using AJAX call.

Now Lets quickly test our web service if it is returning the correct data or not. Press ctrl + F5.

WebServiceCheck

Step 7: Add a webform to the project.

Step 8: Add the following references in the head section of the HTML.

    <script src="DataTables/jQuery-2.2.0/jquery-2.2.0.js"></script>
    <script src="DataTables/DataTables-1.10.11/js/jquery.dataTables.js"></script>
    <link href="DataTables/DataTables-1.10.11/css/jquery.dataTables.css" rel="stylesheet" />
    <link href="DataTables/Bootstrap-3.3.6/css/bootstrap.css" rel="stylesheet" />

The above references are of core jQuery, datatables plugin jquery, datatables plugin css and bootstrap css.

Step 9: Add the following HTML code to the Body tag.

<body>
    <form id="form1" runat="server">
        <div style="padding10pxborder5px solid blackmargin-top50px" class="container-fluid">
            <div>
                <b class="label label-danger" style="padding8.5px">Click to Show or Hide Column:</b>
                <div class="btn-group btn-group-sm">
                    <a class="showHide btn btn-primary" data-columnindex="0">ID</a>
                    <a class="showHide btn btn-primary" data-columnindex="1">FirstName</a>
                    <a class="showHide btn btn-primary" data-columnindex="2">LastName</a>
                    <a class="showHide btn btn-primary" data-columnindex="3">FeesPaid</a>
                    <a class="showHide btn btn-primary" data-columnindex="4">Gender</a>
                    <a class="showHide btn btn-primary" data-columnindex="5">Email</a>
                    <a class="showHide btn btn-primary" data-columnindex="6">TelephoneNumber</a>
                    <a class="showHide btn btn-primary" data-columnindex="7">Date of Birth</a>
                </div>
            </div>
            <br />
            <table id="studentTable" class="table table-responsive table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Fees Paid</th>
                        <th>Gender</th>
                        <th>Email</th>
                        <th>Telephone Number</th>
                        <th>Date of Birth</th>
                    </tr>
                </thead>
                <tfoot>
                    <tr>
                        <th>ID</th>
                        <th>First Name</th>
                        <th>Last Name</th>
                        <th>Fees Paid</th>
                        <th>Gender</th>
                        <th>Email</th>
                        <th>Telephone Number</th>
                        <th>Date of Birth</th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </form>
</body>

We have just declared a table with header and footer. The main content will be displayed using jQuery AJAX call using our web service.

Step 10: Add the custom CSS to the Head section.

    <style>
        .showHide {
            cursorpointer;
        }
    </style>

Step 11: Add the following jQuery Code to the Head section.

    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "studentService.asmx/GetStudents",
                success: function (data) {
                    var datatableVariable = $('#studentTable').DataTable({
                        data: data,
                        columns: [
                            { 'data''iD' },
                            { 'data''firstName' },
                            { 'data''lastName' },
                            {
                                'data''feesPaid''render'function (feesPaid) {
                                    return '$ ' + feesPaid;
                                }
                            },
                            { 'data''gender' },
                            { 'data''emailId' },
                            { 'data''telephoneNumber' },
                            {
                                'data''dateOfBirth''render'function (date) {
                                    var date = new Date(parseInt(date.substr(6)));
                                    var month = date.getMonth() + 1;
                                    return date.getDate() + "/" + month + "/" + date.getFullYear();
                                }
                            }]
                    });
                    $('#studentTable tfoot th').each(function () {
                        var placeHolderTitle = $('#studentTable thead th').eq($(this).index()).text();
                        $(this).html('<input type="text" class="form-control input input-sm" placeholder = "Search ' + placeHolderTitle + '" />');
                    });
                    datatableVariable.columns().every(function () {
                        var column = this;
                        $(this.footer()).find('input').on('keyup change'function () {
                            column.search(this.value).draw();
                        });
                    });
                    $('.showHide').on('click'function () {
                        var tableColumn = datatableVariable.column($(this).attr('data-columnindex'));
                        tableColumn.visible(!tableColumn.visible());
                    });
                }
            });
 
        });
    </script>

Explanation:

1. We use the jquery ajax function to call our web service by mentioning its URL in the URL option.

2. If the call to the service is success, then we call DataTable function of the datatables plugin API which converts our table into a multi-purpose table which can help to show data, filter data, sort data, paging of data, hiding / showing columns etc.

3. We specify the columns that we want to display after getting data from the AJAX call.

4. To allow searching on each column, we use the each function of jQuery and append an input element which displays a textbox at the bottom of each column.

5. To show/hide columns, we are using visible function of jQuery and data-columnindex attribute.

Step 12: Press Ctrl + F5 together and you will see the following output and this is what we want to achieve.

Please comment if I missed anything or give your reviews. If you like my tutorial, please visit my blog and read my other articles too and share. Thanks.