Pages

Saturday, 30 March 2013

CRUD Operation in ASP.NET Web API with Example

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 :

(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 :

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

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 :

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

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 :

(To view original image , click on image)

Set Controller Name :

(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:

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:

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.

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:

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:

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.

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.

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.