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.

Basics of WCF Service with Hosting and Consuming using ASP.NET

Description – In this tutorial, we will learn

  • How to create a WCF Service
  • How to create Service Endpoints
  • How to Host the Service over IIS
  • How to Consume the service using ASP.NET Web application

Step 1: First open Visual Studio (any version) and Create a new Class Library project.

Step 2: Once the project gets created, delete the Class1.cs file which is auto-generated.

Step 3: Right Click on Project Name and Add a WCF Service.

Step 4: Once the WCF Service is added to the project, it will add two types of files mentioned below.

As you can see above, System.ServiceModel is added to the reference libraries as this is the main .NET assembly which supports WCF Services. So, it is a must.

Step 5: First open IDemoService.cs file and replace the code with the below mentioned code.

using System.ServiceModel;
 
namespace DemoWCFService
{
    [ServiceContract//Till will tells the class file that this is a WCF Service
    public interface IDemoService
    {
        [OperationContract//This will expose the Operations that can be operated using this WCF Service
        string GetResponse(); //This is the Method name implementation. 
    }
}

As you can see above, System.ServiceModel is referenced in the using statements.

IDemoService interface is decorated with [ServiceContract] attribute which tells the project that this is a WCF Service.

GetResponse() is a custom method which returns string and it is also decorated with [OperationContract] attribute, which tells that this method can be consumed by client.

Step 6: Open DemoService.cs file and replace the code with the below mentioned code.

namespace DemoWCFService
{
    public class DemoService : IDemoService
    {
        string IDemoService.GetResponse() => "This is the Response from WCF Service.";
    }
}

As it is very simple to understand, that the method that we have declared in the Interface file is implemented here and it is returning the simple text.

Step 7: Now comes the main concept i.e. Endpoints.

Endpoints are the access points for the client applications to access the WCF Service for request and response functionality. They have main 3 properties:

  • Address – it tells at which location the service is hosted
  • Type of Binding – it specifies that in which format the data is to be exchanged
  • Contract – it is actually used to specify the interface name that we have just created. It tells which methods are accessible to the client.
<configuration>
    <system.serviceModel>
        <behaviors>
            <serviceBehaviors>
                <behavior name="mexBehaviour">
                    <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
                    <serviceDebug includeExceptionDetailInFaults="false" />
                </behavior>
            </serviceBehaviors>
        </behaviors>
        <services>
            <service name="DemoWCFService.DemoService" behaviorConfiguration="mexBehaviour">
                <endpoint address="" binding="basicHttpBinding" contract="DemoWCFService.IDemoService">
                    <identity>
                        <dns value="localhost" />
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
                <host>
                    <baseAddresses>
                        <add baseAddress="http://localhost:8733/DemoWCFService/DemoService/" />
                    </baseAddresses>
                </host>
            </service>
        </services>
    </system.serviceModel>
</configuration>

You will find a file named app.config, the above code is to be pasted in that file. If you are using Visual Studio 2013 and above, so this file with this code will be autogenerated but not in the earlier versions.

Now let’s have a look at the app.config file code.

  • In the behaviours element, you can see that a tag name serviceMetadata is added. This tag allows the MetaData of the service to be available to the client in the form of WSDL document. If you wish to know what is WSDL document, I will explain that in a later tutorial but for now think it to be a document which shares data to the client.
  • In the services tag, we have named the service which is the combination of namespace of class file followed by classname.
  • Then we have specified endpoint (explained above), address property has been left blank, but you can give it any meaningful name, binding is basic HTTP binding, contract name is the name of the interface. Identity element is used to specify that we want to host the service at localhost means using IIS.
  • Another endpoint is being mentioned which allows WSDL document to be generated.
  • Then in the host address, we have added the baseAddress as localhost followed by port number of local system.

Now we have completed creating our service. Now we need a hosting application which will host it over HTTP Protocol.

Step 8: Now add a new Windows Console application project to the same solution.

Once the project is created, Add a reference to System.ServiceModel assembly and the WCF Service project.

Now open Program.cs file and replace the code with the below one.

using System;
using DemoWCFService;
using System.ServiceModel;
 
namespace DemoServiceHost
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var host = new ServiceHost(typeof(DemoService)))
            {
                host.Open();
                Console.WriteLine("The Host Started Successfully at " + DateTime.Now);
                Console.ReadLine();
            }
        }
    }
}

In the above code, we have created the object of ServiceHost class and pass the type of service to its constructor. The rest of the code is self explanatory.

Now in the App.config file, add the same code as that of the WCFService project’s App.config file that we just discussed above.

Set this as Startup project and run the application using Ctrl + F5 keys together, a console window will open which confirms that your service is now hosted.

Now its the time to consume that service in an ASP.NET Web application

Step 9: Add a new ASP.NET Web Application project to the same solution.

Step 10: First thing to keep in mind is that the service host should be running to be consumed. So, please go to folder of your Service host project and find the bin folder, there you will find exe file, run that in the Administrator mode.

Step 11: Lets consume the WCF Service that we created to generate the proxy classes so that we can use them.

Step 12: Add a new Webform to the project and press f7 key to move to the source code file.

Add the following code to the Page_Load event.

using System;
using DemoWCFServiceClient.DemoWCFServiceConsumer;
 
namespace DemoWCFServiceClient
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var client = new DemoServiceClient();
            Response.Write(client.GetResponse()); 
        }
    }
}

Just you need, is to add the Service proxy class in the using directive and in Page_Load() event, we create instance of the client and the method of the WCF Service will be automatically visible to the instance as shown in the above images.

Now, finally you have consumed the service, lets run the project and check if everything is fine but before that we need to do some settings to run the host and web application at the same time.

Just follow the below two steps:

Now press Ctrl + f5 together and web page will load and the response from wcf service will be displayed on the page as shown below.

If I missed something, please comment it so that I can update OR give your valuable feedback and share.

Enjoy coding!!