Creating-WebApi-Project-with-CURD-Operation
B Sahoo Posted On : 02/04/2013
About Author
Biswaranjan Sahoo have good working and teching experience in Microsoft technology.
Creating WebApi Project with CURD Operation
CRUD stands for "Create, Read, Update, and Delete," which are the four basic database operations. Many HTTP services also model CRUD operations through REST or REST-like APIs.
In this tutorial, you will build a very simple web API to manage a list of products. Each product will contain a name, price, and category (such as "toys" or "hardware"), plus a product ID.
Methods
The four main HTTP methods (GET, PUT, POST, and DELETE) can be mapped to CRUD operations as follows:
• GET retrieves the representation of the resource at a specified URI. GET should have no side effects on the server.
• PUT updates a resource at a specified URI. PUT can also be used to create a new resource at a specified URI, if the server allows clients to specify new URIs. For this tutorial, the API will not support creation through PUT.
• POST creates a new resource. The server assigns the URI for the new object and returns this URI as part of the response message.
• DELETE deletes a resource at a specified URI.
Create a New Web API Project
Start by running Visual Studio and select New Project from the Startpage. Or, from the File menu, select New and then Project

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET MVC 4 Web Application. Name the project "ProductStore" and clickOK.

 


 

In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.



Adding a Model

A model is an object that represents the data in your application. In ASP.NET Web API, you can use strongly typed CLR objects as models, and they will automatically be serialized to XML or JSON for the client.

For the ProductStore API, our data consists of products, so we'll create a new class named Product.

If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context meny, select Add, then select Class. Name the class "Product".

 



Add the following properties to the Product class.


 

namespace ProductStore.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Category { get; set; }
        public decimal Price { get; set; }
    }
}
Adding a Repository

We need to store a collection of products. It’s a good idea to separate the collection from our service implementation. That way, we can change the backing store without rewriting the service class. This type of design is called the repository pattern. Start by defining a generic interface for the repository.

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

 


 

 

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 "IProductRepository".


 


Add the following implementation:

 

 

 


 

namespace ProductStore.Models
{
    public interface IProductRepository
    {
        IEnumerable<Product> GetAll();
        Product Get(int id);
        Product Add(Product item);
        void Remove(int id);
        bool Update(Product item);
    }
}

Now add another class to the Models folder, named "ProductRepository." This class will implement theIProductRespository interface. Add the following implementation:

namespace ProductStore.Models

{

    public class ProductRepository : IProductRepository

    {

        private List<Product> products = new List<Product>();

        public ProductRepository()

        {

            Add(new Product {Id=1, Name = "Tomato soup", Category = "Groceries", Price = 1.39M });

            Add(new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M });

            Add(new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M });

        }

 

        public IEnumerable<Product> GetAll()

        {

            return products;

        }

 

        public Product GetCategory(string category)

        {

            return products.Find(p => p.Category == category); ;

        }

 

 

 

        public Product Get(int id)

        {

            return products.Find(p => p.Id == id);

        }

 

        public Product Add(Product item)

        {

            if (item == null)

            {

                throw new ArgumentNullException("item");

            }

            products.Add(item);

            return item;

        }

 

        public void Remove(int id)

        {

            products.RemoveAll(p => p.Id == id);

        }

 

        public bool Update(Product item)

        {

            if (item == null)

            {

                throw new ArgumentNullException("item");

            }

            int index = products.FindIndex(p => p.Id == item.Id);

            if (index == -1)

            {

                return false;

            }

            products.RemoveAt(index);

            products.Add(item);

            return true;

        }

    }

}

The repository keeps the list in local memory. 

Adding a Web API Controller
If you have worked with ASP.NET MVC, then you are already familiar with controllers. In ASP.NET Web API, acontroller is a class that handles HTTP requests from the client. The New Project wizard created two controllers for you when it created the project. To see them, expand the Controllers folder in Solution Explorer.
• HomeController is a traditional ASP.NET MVC controller. It is responsible for serving HTML pages for the site, and is not directly related to our web API.
• ValuesController is an example WebAPI controller.
Now add a new controller, as follows:
In Solution Explorer, right-click the the Controllers folder. Select Add and then select Controller.



In the Add Controller wizard, name the controller "ProductsController". In the Template drop-down list, selectEmpty API Controller. Then click Add.



The Add Controller wizard will create a file named ProductsController.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 ProductStore.Models;

Add a field that holds an IProductRepository instance.

 

public class ProductsController : ApiController
{
    static readonly IProductRepository repository = new ProductRepository();
}

To get the list of all products, add this method to the ProductsController class:

public class ProductsController : ApiController
{
    public IEnumerable<Product> GetAllProducts()
    {
        return repository.GetAll();
    }
    // ....
}

To get a product by ID, add this method to the ProductsController class:

   public HttpResponseMessage GetProduct(int id)

        {

            var response = new HttpResponseMessage();

          

            Product item = repository.Get(id);

            if (item == null)

            {

                response = new HttpResponseMessage(HttpStatusCode.NotFound);

            }

            else

            {

              

                response = new HttpResponseMessage(HttpStatusCode.OK);

               

               

            

            }

            return response;

        }

The GetProduct 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 products by category:

public HttpResponseMessage GetProductsByCategory(string category)

        {

            var response = new HttpResponseMessage();

            Product item = repository.GetCategory(category);

            if (item == null)

            {

                response = new HttpResponseMessage(HttpStatusCode.NotFound);

            }

            else

            {

 

                response = new HttpResponseMessage(HttpStatusCode.OK);

 

 

 

            }

            return response;

        }

Creating a Resource

Next, we'll add a method to the ProductsController class to create a new product. Here is a simple implementation of the method:

public HttpResponseMessage PostProduct(Product item)

        {

            item = repository.Add(item);

            var response = new HttpResponseMessage();

 

           

            if (item == null)

            {

                response = new HttpResponseMessage(HttpStatusCode.NotFound);

            }

            else

            {

 

                response = new HttpResponseMessage(HttpStatusCode.OK);

 

 

 

            }

            return response;

          

        }

Updating a Resource

Updating a product with PUT is straightforward:

public HttpResponseMessage PutProduct(int id, Product product)

        {

            var response = new HttpResponseMessage();

            product.Id = id;

 

            if (!repository.Update(product))

            {

                throw new HttpResponseException(HttpStatusCode.NotFound);

            }

            else

            {

 

                response = new HttpResponseMessage(HttpStatusCode.OK);

            }

           return response;

        }

Deleting a Resource

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

public HttpResponseMessage DeleteProduct(int id)

        {

            var response = new HttpResponseMessage();

            Product item = repository.Get(id);

           

            if (item == null)

            {

                throw new HttpResponseException(HttpStatusCode.NotFound);

            }

            else 

            {

                repository.Remove(id);

                response = new HttpResponseMessage(HttpStatusCode.OK);

           

            }

            return response;

         

        }

Post your Suggetion or Comment
Name :
Email Address :
Comment :