Saturday, 30 March 2013

CRUD Operation in ASP.NET Web API with Example

Click Here to Download WebAPICRUDOperation.zip


In this article we are demonstrating how Insert, Update, View and Delete operation works in Output using HTTP service.
We can also call as CRUD (Create, Read, Update, Delete) Operation.

In this WebAPI example we are using following HTTP Methods for CURD Operations.

  • GET method retrieves the data or resources at a specified URI.
  • PUT method updates the data or resource at a specified URI.
  • POST method send data to the specified URI.
  • DELETE method deletes a resource at a specified URI.

Now we are creating project step by step.

STEP 1 :

Create a Web API Project.



For that you need to Start Visual Studio and select New Project from the File menu, select New and then Project. In the Templates pane, Select Visual C# Template from the Installed Templates. In Visual C# section , select Web and then select ASP.NET MVC 4 Web Application. After that give project name "WebAPICRUDOperation" and click OK.

Screenshot :

CRUD Operation in ASP.NET Web API
(To view original image , click on image)



After that the New ASP.NET MVC 4 Project dialog appear, In this, you need to select Web API and select view engine "Razor" this is by default appear so no need to change that after that click OK.

Screenshot :

CRUD Operation in ASP.NET Web API
(To view original image , click on image)



STEP 2 :

Add Model :

Not we start creating customer model.

Open Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class. Add class name "Customer".

Screenshot :

CRUD Operation in ASP.NET Web API
(To view original image , click on image)


Insert following properties in "Customer" class.
    public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Designation { get; set; }
        public decimal Salary { get; set; }

    }


STEP 3

Add Repository :

We need to store a collection of customers. It's a good idea to keep separate the collection from service implementation. This type of design is known as the repository pattern. Now we add a generic interface for the repository.

In Solution Explorer, right-click the Models folder. Select Add, then select New Item.

Screenshot :
CRUD Operation in ASP.NET Web API
(To view original image , click on image)


In the Templates pane, select Installed Templates and expand the C# node.
Under C#, select Code. In the list of code templates, select Interface. Name the interface "ICustomerRepository".

Screenshot :
CRUD Operation in ASP.NET Web API
(To view original image , click on image)


Select Interface:
CRUD Operation in ASP.NET Web API
(To view original image , click on image)


Add the following implementation:
    interface ICustomerRepository
    {
        IEnumerable<Customer> GetAll();
        Customer Get(int id);
        Customer Add(Customer item);
        bool Update(Customer item);
        void Remove(int id);
    }


Now we add another class to the Models folder, named "CustomerRepository".

Screenshot:
CRUD Operation in ASP.NET Web API
(To view original image , click on image)

This class will implement the ICustomerRespository interface.
Add the following implementation:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebAPICRUDOperation.Models
{
    public class CustomerRepository : ICustomerRepository
    {
        private List<Customer> customers = new List<Customer>();
        private int _nextId = 1;

        public CustomerRepository()
        {
            Add(new Customer { Id = 1, Name = "Rajesh", Designation = "Programmer", Salary = 50000 });
            Add(new Customer { Id = 2, Name = "Tom", Designation = "HR", Salary = 40000 });
            Add(new Customer { Id = 3, Name = "Mukesh", Designation = "HR", Salary = 45000 });
            Add(new Customer { Id = 4, Name = "Sachin", Designation = "TL", Salary = 55000 });
            Add(new Customer { Id = 5, Name = "Alex", Designation = "PM", Salary = 60000 });
        }
        public IEnumerable<Customer> GetCustomers()
        {
            return customers;
        }
        public IEnumerable<Customer> GetAll()
        {
            return customers;
        }

        public Customer Get(int id)
        {
            return customers.Find(p => p.Id == id);
        }

        public Customer Add(Customer item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            item.Id = _nextId++;
            customers.Add(item);
            return item;
        }

        public void Remove(int id)
        {
            customers.RemoveAll(p => p.Id == id);
        }

        public bool Update(Customer item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            int index = customers.FindIndex(p => p.Id == item.Id);
            if (index == -1)
            {
                return false;
            }
            customers.RemoveAt(index);
            customers.Add(item);
            return true;
        }

    }
}

The repository keeps the list in local memory. This is OK for a tutorial, but in a real application, you would store the data externally, either a database or in cloud storage. The repository pattern will make it easier to change the implementation later.


STEP 4 :

Add Controller :

These controllers are available in "Controllers" folder. There are two controller files in "Controllers" folder first HomeController.cs and second ValuesController.cs.

Now you delete ValuesController file and Add a new controller file.

In Solution Explorer, right-click on the Controllers folder. Select Add and then select Controller and give name "CustomersController.cs" file. This will create new controller in "Controllers" Folder.


Screenshot :
CRUD Operation in ASP.NET Web API
(To view original image , click on image)


Set Controller Name :

CRUD Operation in ASP.NET Web API
(To view original image , click on image)


The Add Controller wizard will create a file named CustomersController.cs in the Controllers folder.
If this file is not open already, double-click the file to open it. Add the following using statement:

using WebAPICRUDOperation.Models;

Add a field that holds an ICustomerRepository instance.

public class CustomersController : ApiController
{
    static readonly ICustomerRepository repository = new CustomerRepository();
}

Calling new ProductRepository() in the controller is not the best design because it ties the controller to a particular implementation of IProductRepository. For a better approach, see Using the Web API Dependency Resolver.


STEP 5

Getting a Resource :

The Customer API will expose several "read" actions as HTTP GET methods. Each action will correspond to a method in the CustomersController class.
Action HTTP Method Relative URI
Get All Customers GET /api/customers
Get Customer By Id GET /api/customers/id
Get Customers By Designation GET /api/customers/?designation=designation

To get the list of all customer, add this method to the CustomersController class:

    public class CustomersController : ApiController
    {
        static readonly ICustomerRepository repository = new CustomerRepository();

        public IEnumerable<Customer> GetAllCustomers()
        {
            return repository.GetAll();
        }
    }
}

The method name starts with "Get", so by convention it maps to GET requests. Also, because the method has no parameters, it maps to a URI that does not contain an "id" segment in the path.

To get a customer by ID, add this method to the CustomersController class:

        public Customer GetCustomer(int id)
        {
            Customer item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return item;
        }

This method name also starts with "Get", but the method has a parameter named id. This parameter is mapped to the "id" segment of the URI path. The ASP.NET Web API framework automatically converts the ID to the correct data type (int) for the parameter.

The GetCustomer method throws an exception of type HttpResponseException if id is not valid. This exception will be translated by the framework into a 404 (Not Found) error.

Finally, add a method to find customers by designation :

        public IEnumerable<Customer> GetCustomersByDesignation(string designation)
        {
            return repository.GetAll().Where(
                p => string.Equals(p.Designation, designation, StringComparison.OrdinalIgnoreCase));
        }

If the request URI has a query string, Web API tries to match the query parameters to parameters on the
controller method. Therefore, a URI of the form "api/customers?designation=designation" will map to this method.


STEP 6 :

Creating a Resource :

Next, we will add a method to the CustomersController class to create a new customer.
Here is a simple implementation of the method:

        public HttpResponseMessage PostCustomer(Customer item)
        {
            item = repository.Add(item);
            var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, item);

            string uri = Url.Link("DefaultApi", new { id = item.Id });
            response.Headers.Location = new Uri(uri);
            return response;
        }

Note two important things about this method:

  • The method name starts with "Post...". To create a new customer, the client sends an HTTP POST request.
  • The method takes a parameter of type Customer. In Web API, parameters with complex types are deserialized from the request body. Therefore, we expect the client to send a serialized representation of a customer object, in either XML or JSON format.

This implementation will work, but it is not quite complete. Ideally, we would like the HTTP response
to include the following:
  • Response code : By default, the Web API framework sets the response status code to 200 (OK).
  • Location : When the server creates a resource, it should include the URI of the new resource in the Location header of the response.

In ASP.NET Web API it easy to manipulate the HTTP response message.


Notice that the method return type is now HttpResponseMessage. By returning an HttpResponseMessage instead of a Customer, we can control the details of the HTTP response message, including the status code and the Location header.


For Updating a Customer with PUT is very simple:

        public void PutCustomer(int id, Customer customer)
        {
            customer.Id = id;
            if (!repository.Update(customer))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

The method name starts with "Put...", so Web API matches that it to PUT requests. The method takes two parameters, the customer ID and the updated Customer object.

The id parameter is taken from the URI path, and the Customer object parameter is deserialized from the request body. By default, the ASP.NET Web API framework takes simple parameter types from the route and complex types from the request body.

Deleting a Resource :

To delete a resource, define a "Delete..." method.

        public void DeleteCustomer(int id)
        {
            Customer item = repository.Get(id);
            if (item == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            repository.Remove(id);
        }

If a DELETE request succeeds, it can return status 200 (OK) with an entity-body that describes the status. Status 202 (Accepted) if the deletion is still pending; or status 204 (No Content) with no entity body.
In this case, the DeleteCustomer method has a void return type, so ASP.NET Web API automatically translates this into status code 204 (No Content).

Here is example of CRUD Operation:
In this example we can Create, Read, Update and Delete customers with JQuery and JSON request.

Here is output screent for that :

Output (Initial Page View)  :

CRUD Operation in ASP.NET Web API
(To view original image , click on image)

Output (Get specified customer id records and display)  :

CRUD Operation in ASP.NET Web API
(To view original image , click on image)

Output (Update Customer Records)  : 

CRUD Operation in ASP.NET Web API
(To view original image , click on image)

Output (Adding New Customer)  :

CRUD Operation in ASP.NET Web API
(To view original image , click on image)

Output (New Customer Added)  : 

CRUD Operation in ASP.NET Web API
(To view original image , click on image)


Here is first basic article regarding ASP.NET Web API. Visit here... 

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles according to that.



1 comment:

  1. Nice example with source code. Only thing for which i was looking here and there is the delete functionality. Its not here even. But well thanx for the rest

    ReplyDelete