CRUD operation using ASP.NET Web Api and MVC 4 – Part 1
ASP.NET Web API is a framework for building HTTP services using the .NET Framework. Since HTTP services are supported virtually by any platform so its is a powerful tool that can reach to broader range of client like Native mobile applications, browsers, desktop applications, etc.
Being novice on this topic I just tried to flex my skills to create a basic application to demonstrate ASP.NET Web Api using ASP.NET MVC 4, jQuery, EF Code First approach and SQL Server Database. But I hope this example will give you enough confidence to get these technologies rolling in real time environment using MVC Web Api and MVC 4 as Client.
Since here I have not covered very basics of MVC and Web Api so if you are beginner to ASP.NET MVC, jQuery, etc., I recommend you to go through some good MSDN Articles first.
Before you start you may need to install ASP.NET MVC 4 Beta release in you system from the following location: http://www.asp.net/mvc/mvc4
This post was getting very large to fit into one single post so I have divided into two different post which is as follows,
- CRUD operation using ASP.NET Web Api and MVC 4 – Part 1 (Creating a Web Api Service)
- CRUD operation using ASP.NET Web Api and MVC 4 – Part 2 (Creating a Client application which will consume Web Api Services)
1. Creating a Web Api Service.
Now lets start, as usual first you will have to create a new project from VS2010, by selecting the New Project –> Web –> ASP.NET MVC 4 Web Application template.
Give a name or select the default name for you project and then Click on Ok button, you will get the following screen where you can select your desired template for ASP.NET MVC 4 application type, for this example we have to Select Web API template using Razor view engine.
Once you click okay, you will get the default project solution structure for ASP.NET MVC Application, you may not see any difference between you normal MVC application or Web Api application. Now lets get into the code to see what additional features and class libraries are provided by Web Api project which makes it different and better from you normal MVBC Application. To show this lets first open the ValuesController provided by the template. In this screen you can see the ValuesController is derived from ApiController of System.Web.Http library instead of Controller of System.Web.Mvc library with the default method provided for GET, POST, PUT and DELETE methods. And the other difference you can notice here is the action methods used here is not returning ActionResult, JsonResult or FileResult, etc., instead it just returns data.
Now the only thing left for us to customize or extend this classes to serve our purpose, Web Api is basically meant to expose our interfaces as a RESTful. To start this first I have created a simple Contact table as given below. This table is used to Create, Read, Update and Delete a record.
Now I have added a ADO.NET Entity Data Model to connect to database, and on top of that I have created a simple repository where I have defined my contracts for Add, Update, Delete, GetAll and GetById method on my ContactDetail tables.
Now I will derive my IContactRepository in ContactModel class where I am going to have my implementation of all the methods using EntityFramework DBContext classes. Given below is the code for ContactModel class.
1: public class ContactModel : IContactRepository
2: {
3: ContactEntities context = new ContactEntities();
4:
5: /// <summary>
6: /// Gets All Contact
7: /// </summary>
8: /// <returns>All Contact Details</returns>
9: public IEnumerable<ContactDetail> GetAll()
10: {
11: return context.ContactDetails;
12: }
13:
14: /// <summary>
15: /// Get Contact by Contact ID
16: /// </summary>
17: /// <param name="contactId">Contact Id</param>
18: /// <returns>Contact Detail</returns>
19: public ContactDetail GetById(int contactId)
20: {
21: IQueryable<ContactDetail> customers = context.ContactDetails.Where(a => a.ContactId == contactId);
22: return customers.FirstOrDefault();
23: }
24:
25: /// <summary>
26: /// Updates Existing Contact
27: /// </summary>
28: /// <param name="contact">Contact</param>
29: /// <returns>result</returns>
30: public int Update(ContactDetail contact)
31: {
32: ContactDetail updateContact = context.ContactDetails.FirstOrDefault(c => c.ContactId == contact.ContactId);
33: updateContact.FirstName = contact.FirstName.Trim();
34: updateContact.MiddleName = contact.MiddleName.Trim();
35: updateContact.LastName = contact.LastName.Trim();
36: updateContact.EmailAddress = contact.EmailAddress.Trim();
37:
38: return context.SaveChanges();
39: }
40:
41: /// <summary>
42: /// Adds New Contact
43: /// </summary>
44: /// <param name="contact">Contact</param>
45: public ContactDetail Add(ContactDetail contact)
46: {
47: var addedContact = context.ContactDetails.Add(contact);
48: context.SaveChanges();
49:
50: return addedContact;
51: }
52:
53: /// <summary>
54: /// Deletes Contact
55: /// </summary>
56: /// <param name="contactId">Contact ID</param>
57: public void Delete(int contactId)
58: {
59: ContactDetail contact = context.ContactDetails.FirstOrDefault(a=>a.ContactId == contactId);
60: context.ContactDetails.Remove(contact);
61: context.SaveChanges();
62: }
63: }
Now before I go for my controller, I need to register my controller and default routes, in Global.asax.cs file, but in our example we don’t need to worry about this, as this is already provided by the default ASP.NET MVC 4 Web Api template. But in case if you have any specific path you want to register then you will have to define it from here.
Now my next Step will be to define my actual API’s in the controller classes, completed code of my API class is given below.
1: using System.Collections.Generic;
2: using System.Web.Http;
3: using MvcAppWebApi.Models;
4: using System.Net;
5:
6: namespace MvcAppWebApi.Controllers
7: {
8: public class ValuesController : ApiController
9: {
10: IContactRepository repository = new ContactModel();
11:
12: // GET /api/values
13: [HttpGet]
14: public IEnumerable<ContactDetail> Get()
15: {
16: return repository.GetAll();
17: }
18:
19: // GET /api/values/5
20: [HttpGet]
21: public ContactDetail Get(int id)
22: {
23: ContactDetail contact = repository.GetById(id);
24: return contact;
25: }
26:
27: // POST /api/values
28: [HttpPost]
29: public void PostContact(ContactDetail contact)
30: {
31: repository.Add(contact);
32: }
33:
34: // PUT /api/values
35: [HttpPut]
36: public void PutContact(ContactDetail contact)
37: {
38: if (repository.Update(contact)==0)
39: {
40: throw new HttpResponseException(HttpStatusCode.NotFound);
41: }
42: }
43:
44: // DELETE /api/values/5
45: [HttpDelete]
46: public void Delete(int id)
47: {
48: repository.Delete(id);
49: }
50: }
51: }
From the above code my ValuesController API will expose the following methods
In the Action list above, I have exposed the following methods as Web Api,
-
Get – This method calls the GetAll method from Repository and returns all the Contacts from the Database as IEnumerable<ContactDetail>
-
Get – This method accepts ContactId as parameter and calls the GetById method of Repository which finally returns corresponding ContactDetail.
-
Add – This action method calls the Add method of Repository to add a new ContactDetail.
-
Update – This method accepts ContactDetail as a parameter which in turns calls Update method of Repository to update the selected ContactDetail.
-
Delete – This method accepts ContactId as input parameter and in turn calls the Delete method of Repository, Using the ContactId repository retrieves the Contact from the context and finally delete the ContactDetail from the Database.
To customize the relative URI, with different names like “mycompany/customers” you have to change the Register route from Global.asax.cs and the controller name. In the below figure I have left the default route name as “api” this can be changed to “mycompany” and rename the “ValuesController” to “CustomersController” this will give you the Relative URI as “mycompany/customers”
Now my Web Api is ready to take request, to test the API run the application first and press F12 to run the developer toolbar. Now in the developer toolbar you need to select the Network Tab and Press the Start Capture button, Once you developer toolbar is ready to monitor the browser request and response, type the URL along with the existing URL of the browser as “/api/values/” this should give you the Result as 200 which means GET request is successfully executed,
Now go to the Detailed View of the selected request. and select the response body tab, this is displaying my response returned from the API, containing all the Contact Details which is present in my Database.
Similarly you can test the “api/values/{id}” URI also.
In my next Post I am going to create a Client Application which will consume the above created Services, for Get, GetById, Update, Add and Deleting a Contact using jQuery.
2. CRUD operation using ASP.NET Web Api and MVC 4 – Part 2 (Creating a client application which will consume Web Api Services) – Coming Soon