CRUD Operation On ASP.Net Web API From .NET Client

In this article we will learn how to work with CRUD operations and the ASP.NET Web API. We will learn:

  1. To create CRUD operation on ASP.NET Web API
  2. Using  Entity model to create model
  3. Creating repository to perform CRUD operation
  4. Consuming service in .NET Console Client 

I can draw the architecture of this article as in the following:

CRUD-operation-on-ASP.NET-1.jpg
 
Let us follow a step-by-step approach to perform the CRUD operations using an ASP.NET Web API service.
 
Create ASP.Net Web API
 
In this part of the article, we will learn to create an ASP.NET Web API. To create it, launch Visual Studio and create a project by choosing the "ASP.NET MVC 4 Web Application" template.

CRUD-operation-on-ASP.NET-2.jpg

Next you select Web API from the existing project template. Ensure to select "Razor" as the "View engine" in the drop down.

CRUD-operation-on-ASP.NET-3.jpg
 
Next we need to add a model. We will use an ADO.Net Entity model to create a model out of the database. To add a model, right-click on the Models folder and select "Add New Item".  Next from the "Data" tab select "ADO.NET Entity Data Model".

CRUD-operation-on-ASP.NET-4.jpg

Next select "Generate" from the database options and click on "Next".

CRUD-operation-on-ASP.NET-5.jpg
 
In the next dialog box, you need to configure the Connection Properties. Here select the Northwind database after giving the server name.

CRUD-operation-on-ASP.NET-6.jpg
 
After configuring the connection, you will get the Entity Data Model Wizard populated with the connection string as below. Click on "Next" to proceed further.

CRUD-operation-on-ASP.NET-7.jpg
 
Here you need to select the tables, views and so on. For the purpose of this article, let us select three tables, Customers, Employees and Products. After selecting tables click on "Finish" to create a model of the database in the project.

CRUD-operation-on-ASP.NET-8.jpg
 
We will now work with the Product table. To perform CRUD operations on this, let us proceed to creating a Repository. To create it right-click on the model and add an Interface from the "Code" tab.  I am giving the name "IProductRepository".

CRUD-operation-on-ASP.NET-9.jpg

In this interface we will define all the operations needed to be performed on the Product table.  The interface is defined as below:

using System.Collections.Generic;

namespace NorthwindService.Models

{

    public interface IProductRepository

    {

        IEnumerable<Product> GetProducts();

        bool AddProduct(Product p);

        bool UpdateProduct(Product p);

        bool DeleteProduct(int ProductID);

    }

}
 
Next we need to implement CRUD operations. To do that, add a class and implement "IProductRepository" in that class. Let us implement all four operations one by one.

Note : All these operations would be defined under the ProductRepository class.

We can fetch all the Products as below using a simple LINQ.
 
public IEnumerable<Product> GetProducts()
{

  NorthwindEntities entities = new NorthwindEntities();

  var products = from r in entities.Products select r;

  return products.ToList();

}
 
A product can be added as below,
 

public bool AddProduct(Product p)

{

    try

    {

        NorthwindEntities entities = new NorthwindEntities();

        entities.Products.Add(p);

        entities.SaveChanges();

        return true

    }

    catch (Exception ex)

    {

       return false

    }

 }


Product can be updated as below,
 

public bool UpdateProduct(Product p)

{

     try

    {

        NorthwindEntities entities = new NorthwindEntities();

        Product proudctToUpdate = (from r in entities.Products where 

                                      r.ProductID == p.ProductID select r).FirstOrDefault();

        proudctToUpdate.ProductName = p.ProductName;

        proudctToUpdate.UnitPrice = p.UnitPrice;

        entities.SaveChanges();

       return true;

    }

   catch (Exception ex)

   {

        return false;

   }

}


Product can be deleted as below,
 

public bool DeleteProduct(int productID)

{

    try

    {

        NorthwindEntities entities = new NorthwindEntities();

        Product proudctToDelete = (from r in entities.Products

                                   where

                                   r.ProductID == productID

                                   select r).FirstOrDefault();

        entities.Products.Remove(proudctToDelete);

        entities.SaveChanges();

        return true;

    }

    catch (Exception ex)

    {

        return false;

    }

}
 
After creating a repository for CRUD operations, let us proceed to creating a Controller.  To create a Controller, right-click on the Controller folder and select "Add new Controller". You need to rename the Controller name to "ProductsController".

CRUD-operation-on-ASP.NET-10.jpg
 
You will get a controller class created as in the following. Ensure that you have changed "Controller" to "ApiController".

CRUD-operation-on-ASP.NET-11.jpg


Now we can create CRUD operations as below.

Products can be fetched as in the following:
 

static readonly IProductRepository repository = new ProductRepository();

public IEnumerable<Product> GetProducts()

{

   return repository.GetProducts();

}
 
 A new record can be created as in the following. We are passing Product as a resource to be created here. While creating a new record ensure:

  1. Action name is PostProduct. Essentially Action name should be started with Post to perform insert operation

  2. Pass Product as input parameter

  3. Return HttpResponse

We are calling the AddProduct method of the Repository class. Repository class is returning true on successful insertion of a record. We are checking the returned value and constructing the returned HttpResponse.
  

public HttpResponseMessage PostProduct(Product p)

{

    bool result = repository.AddProduct(p);

    HttpResponseMessage response;

    if(result)

    {

    response  = Request.CreateResponse(System.Net.HttpStatusCode.Created);

    }

    else

    {

        response = Request.CreateResponse(System.Net.HttpStatusCode.ExpectationFailed);

    }

    return response ; 

}
 
Modification of the resource or Put operation can be performed as below. It is exactly the same as a Put operation with two differences:

  1. Action or function name starts from Put

  2. UpdateProduct function of Repository class is being called

public HttpResponseMessage PutProduct(Product p)

{

    bool result = repository.UpdateProduct(p);

    HttpResponseMessage response;

    if(result)

    {

        response = Request.CreateResponse(System.Net.HttpStatusCode.OK);

     }

    else

    {

         response  = Request.CreateResponse(System.Net.HttpStatusCode.ExpectationFailed);       

    }

    return response ;  

}
 
The deletion of a resource or a Put operation can be performed as below. It is exactly the same as other operations with two differences:

  1. Action or function name starts with "Delete"

  2. It takes an Id as an input parameter to delete the record with the specified id

  3. The "DeleteProduct" function of the Repository class is being called.

public HttpResponseMessage DeleteProduct(int id)

{

    bool result = repository.DeleteProduct(id);

    HttpResponseMessage response;

    if(result)

    {

    response  = Request.CreateResponse(System.Net.HttpStatusCode.OK);

    }

    else

    {

        response = Request.CreateResponse(System.Net.HttpStatusCode.ExpectationFailed);            

    }

    return response ; 

}


This is what all you need to do to create an ASP.NET Web API  with CRUD operations on a Northwind database.
 
Creating .NET or Console Client
 
We will now create the .NET Console client to consumer service we created earlier. To create the Console Application project, you need to select the "Console Application" project template from the Windows tab. After creating the project, right-click on the project and select "Manage Nuget packages".  Here search for the Microsoft.AspNet.WebApi.Client library. Install this NuGet package in the client project. 

CRUD-operation-on-ASP.NET-12.jpg
 
After installing the package, add the following references to the project:

using System.Net.Http;

using System.Net.Http.Headers;
 
Before we perform any operation, first initialize the following in the project
:

  1. Initializing HttpClient

  2. Setting base address

  3. Setting Http Request Header as JSON

 HttpClient client = new HttpClient();

client.BaseAddress = new Uri("http://localhost:37780/api/");

client.DefaultRequestHeaders.Accept.Add(

new MediaTypeWithQualityHeaderValue("application/json"));
 
After initializing HttpClient and base address, we need to create a client-side representation of the Product class. Let us create a Product class at the client side. Ensure that the definition of the class is the same as the server side. The client-side Product class is as in the following: 
 

public class Product

{

    public int ProductID { get; set; }

    public string ProductName { get; set; }

    public Nullable<int> SupplierID { get; set; }

    public Nullable<int> CategoryID { get; set; }

    public string QuantityPerUnit { get; set; }

    public Nullable<decimal> UnitPrice { get; set; }

    public Nullable<short> UnitsInStock { get; set; }

    public Nullable<short> UnitsOnOrder { get; set; }

    public Nullable<short> ReorderLevel { get; set; }

    public bool Discontinued { get; set; }

}
 
Read Products from service
 
You can fetch all the Products as in the following:
 

HttpResponseMessage response = client.GetAsync("products").Result;

    if (response.IsSuccessStatusCode)

    {

        var products = response.Content.ReadAsAsync<IEnumerable<Product>>().Result;

        foreach (var p in products)

        {

            Console.WriteLine("{0}\t{1};\t{2}", p.ProductName, p.UnitPrice, p.QuantityPerUnit);

        }

    }

    else

    {

        Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

    }


 We are fetching records by performing the following steps in the code above. 
 

  1. Records are being fetched using the GetAsync method of the HttpClient class.
  2. We are passing the name of the entity in GetAsync
  3. After fetching records, reading JSON data using the Conent.ReadAsAsync() method of HttpResponseMessage
  4. If the response is erroneous then we are displaying an error code as output.

Creating a Record
 
 To create or insert a record (in this case Product), we need to do the following:

  1. Create an instance of the product to be inserted
  2. Perform a PostAsJsonAsync operation on HttpClient and pass an entity name and object to be inserted as a parameter
  3. On successful insertion you will get a successful status code else an error code
The following code snippet will create a Product in the database to perform a Put operation using the ASP.NET Web API.
 

 Product p = new Product

 {

     ProductName = "DJ'S Pen",

     QuantityPerUnit = "20",

     Discontinued = true 

 };

 HttpResponseMessage response = client.PostAsJsonAsync("products", p).Result;

 if (response.IsSuccessStatusCode)

{

     Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

}

else

{

     Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

}
 
On successful creation of the record you will get the response as below:

CRUD-operation-on-ASP.NET-13.jpg
 
Updating Record
 
Updating a record is exactly the same as creating a record. Only you need to use the "PutAsJsonAsync()" method.  You can update a record as in the following:
 

Product p = new Product

{

     ProductID = 90,

     ProductName = "DJ'S Bat",

     QuantityPerUnit = "20",

     Discontinued = true

};

HttpResponseMessage response = client.PutAsJsonAsync("products", p).Result;

if (response.IsSuccessStatusCode)

{

     Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

}

else

{

    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

}
 
On successful update you should get a success message as in the following:

CRUD-operation-on-ASP.NET-14.jpg

Deleting Record
 
You can delete a resource using the "DeleteAsync" function. You need to pass the URI of the resource to be deleted.
 

HttpResponseMessage response = client.DeleteAsync("Products/90").Result;

if (response.IsSuccessStatusCode)

{

    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

 }

 else

 {

    Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);

 }


Here 90 is the ProductId we want to delete. On successful deletion you will get a success message as in the following:

CRUD-operation-on-ASP.NET-15.jpg

Conclusion

 

In this article we learned the following:

  1. Using  ADO.NET Entity Model as model in Web API

  2. Creating CRUD operation on ASP.NET Web API

  3. Consuming service in .NET client

I hope you find this article useful. Thanks for reading.

Up Next
    Ebook Download
    View all
    Learn
    View all