DotNetCurry Logo

Creating REST Service using ASP.NET Web API – (Project Tracking Website Part II)

Posted by: Pravinkumar Dabade , on 12/26/2014, in Category AngularJS
Views: 158061
Abstract: This article shows how to build REST based services using ASP.NET Web API

In the first part of our Project Tracking Website Project Tracking Website using AngularJS and ASP.NET Web API, we did a brief overview of why do we need AngularJS, what is AngularJS and an example of using AngularJS. This article is part of a series of articles on how to build interactive web sites using ASP.NET Web API and the popular client side JavaScript library called AngularJS. In this article and the 2nd part of this series, we will build REST based services using ASP.NET Web API and in the subsequent parts, learn how to serve data from this Web API to our AngularJS views.

 

What is REST? REST  stands for REpresentational State Transfer. It is a software design pattern introduced as an alternative to SOAP-based data exchange and is a way for programs to talk over the web.

What is ASP.NET Web API? In its simplest form, a Web API is an API over the web (HTTP) and ASP.NET Web API is a framework that allows you to build Web API’s, i.e. HTTP-based services on top of the .NET Framework using a convention based and similar programming model, as that of ASP.NET MVC. These services can then be used in a broad range of clients, browsers and mobile devices. If you are new to ASP.NET Web API, read Head First into ASP.NET Web API and What's New in ASP.NET Web API 2.0.

We will go ahead and add a Web API project into our existing Solution which we created in the first article.

Open the project “ProjectTrackingWebsite” using Visual Studio Express 2013 for Web. Right click the solution and add a new project. Choose ASP.NET Web Application. Name it as “ProjectTrackingServices” and select the Web API template as shown here:

web-api-template

Once the project has been created, we will use Entity Framework which is Microsoft’s ORM technology to perform CRUD operations against our ProjectTracking database. First add a reference to Entity Framework using NuGet package in our project as shown here:

ef-nuget

Now add a new item into our ProjectTrackingServices. Choose Data section and then choose ADO.NET Entity Data Model

entity-data-model

Name it as ProjectTrackingDB. In the wizard that pops up, choose Generate from database template. Click on the Next button. Now either choose an existing connection (if exists) or create a new connection for ProjectTrackingDB database. In the next step, select all the tables from the database and click on Finish button. This will bring up the ProjectTrackingDB.edmx diagram

edmx-diagram

Now it’s time to create our Web APIs to perform CRUD operations. Right click on the Controllers folder and add a new controller. Choose Web API 2 Controller with read/write actions template as shown here:

web-api-controller

Name it as PTEmployeesController. You will see five different methods in our controller as mentioned below –

· Get – Use it for selecting all the employees

· Get with parameter – Use it for selecting a specific employee

· Post – Use it for inserting employee into Employees table

· Put – Use it for updating existing employee

· Delete – Use it for deleting existing employee

We will write the logic to perform the CRUD operations. Let’s add a new class with the name “EmployeesRepository” which will talk to our ADO.NET Entity framework and help our controller to pull or push the data. Right click on the Models folder and add a class EmployeesRepository. The code that goes into this class is shown below –

 

public class EmployeesRepository
{
    private static ProjectTrackingDBEntities dataContext = new ProjectTrackingDBEntities();
    public static List<Employee> GetAllEmployees()
    {
        var query = from employee in dataContext.Employees
                    select employee;
        return query.ToList();
    }

    public static List<Employee> SearchEmployeesByName(string employeeName)
    {
        var query = from employee in dataContext.Employees
                    where employee.EmployeeName.Contains(employeeName)
                    select employee;
        return query.ToList();
    }

    public static Employee GetEmployee(int EmployeeID)
    {
        var query = from employee in dataContext.Employees
                    where employee.EmployeeID == EmployeeID
                    select employee;
        return query.SingleOrDefault();
    }

    public static List<Employee> InsertEmployee(Employee e)
    {
        dataContext.Employees.Add(e);
        dataContext.SaveChanges();
        return GetAllEmployees();
    }

    public static List<Employee> UpdateEmployee(Employee e)
    {
        var emp = (from employee in dataContext.Employees
                   where employee.EmployeeID == e.EmployeeID
                   select employee).SingleOrDefault();
        emp.EmployeeName = e.EmployeeName;
        emp.Designation = e.Designation;
        emp.ContactNo = e.ContactNo;
        emp.EMailID = e.EMailID;
        emp.SkillSets = e.SkillSets;
        dataContext.SaveChanges();
        return GetAllEmployees();
    }

    public static List<Employee> DeleteEmployee(Employee e)
    {
        var emp = (from employee in dataContext.Employees
                   where employee.EmployeeID == e.EmployeeID
                   select employee).SingleOrDefault();
        dataContext.Employees.Remove(emp);
        dataContext.SaveChanges();
        return GetAllEmployees();
    }
}

 

Now open WebApiConfig.cs file from App_Start folder and add the following code in the Register method –

config.EnableCors();
var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
        json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        config.Formatters.Remove(config.Formatters.XmlFormatter);


 

This code does the following:
1. Converts names of properties to camel case while serializing the objects to JSON

2. Removes XML formatter from Web API’s formatters to make sure JSON data is returned on each request
 

In our PTEmployeesController, we are using new routing configuration introduced in ASP.NET Web API 2.0. So we don’t need default routing configuration. Comment the default routing configuration as shown here:

//config.Routes.MapHttpRoute(
//    name: "DefaultApi",
//    routeTemplate: "api/{controller}/{id}",
//    defaults: new { id = RouteParameter.Optional }
//);


 

For more details on new features introduced in ASP.NET Web API 2.0, check out the article What’s New in ASP.NET Web API 2.0. The method EnableCors() is used to enable Cross Origin Requests in Web APIs. 

Now we will call our repository code into our PTEmployeesController as shown here –

[EnableCors(origins: "http://localhost:55058", headers: "*", methods: "*")]
public class PTEmployeesController : ApiController
{
    // GET api/ptemployees
    [Route("api/ptemployees")]
    public HttpResponseMessage Get()
    {
        var employees= EmployeesRepository.GetAllEmployees();
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
        return response;
    }

    // GET api/ptemployees/5
    [Route("api/ptemployees/{id?}")]
    public HttpResponseMessage Get(int id)
    {
        var employees = EmployeesRepository.GetEmployee(id);
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
        return response;
    }

    [Route("api/ptemployees/{name:alpha}")]
    public HttpResponseMessage Get(string name)
    {
        var employees = EmployeesRepository.SearchEmployeesByName(name);
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
        return response;
    }

    [Route("api/ptemployees")]
    public HttpResponseMessage Post(Employee e)
    {
        var employees = EmployeesRepository.InsertEmployee(e);
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
        return response;
    }

    [Route("api/ptemployees")]
    public HttpResponseMessage Put(Employee e)
    {
        var employees = EmployeesRepository.UpdateEmployee(e);
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
        return response;
    }

    [Route("api/ptemployees")]
    public HttpResponseMessage Delete(Employee e)
    {
        var employees = EmployeesRepository.DeleteEmployee(e);
        HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
        return response;
    }
}


 

It’s time to test our PTEmployeesController. Open the browser. I am using Google Chrome and have typed the following structure in the url (marked with a red box). The output is shown below:
 

emp-controller
 

emp-controller1
 

You can test the rest of the operations using a tool like Fiddler. Take a look at my article on DevCurry.com to do so - Testing CRUD operations in ASP.NET Web API using Fiddler

Now using the steps mentioned above, design the Web API controllers and their repository code in a similar manner – 


  • PTProjectsController and ProjectsRepository
     
  • PTUserStoryController and UserStoryRepository
     
  • PTUserTasksController and UserTasksRepository
     
  • PTManagerCommentsController and ManagerCommentsRepository 

Now our services are ready to use in our ProjectTracking website.

In the next article we will do a brief introduction on how to work with AngularJS Controllers and use these services we just built in our controllers.  

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Pravinkumar, works as a freelance trainer and consultant on Microsoft Technologies. He is having over 10 years of experience in IT and is also a Microsoft Certified Trainer(MCT). He has conducted various corporate trainings on all versions of .NET Technologies including .NET, SharePoint Server, Microsoft SQL Server, Silverlight, ASP.NET, Microsoft PerformancePoint Server 2007 (Monitoring). He is passionate about learning new technologies from Microsoft. You can contact Pravinkumar at dabade[dot]pravinkumar [attherate] gmail[dot]com


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by Pete Carroll on Saturday, January 24, 2015 8:13 AM
Quick question:  shouldn't the UserTaskRespository and the PTUserTaskControler but ProjectTaskRepository and PTProjectTaskController?
Comment posted by sachin on Saturday, February 21, 2015 3:46 AM
Hi,
next part is not added or wat?
Comment posted by sachin on Saturday, February 21, 2015 5:41 AM
Hi,
next part is not added or wat?
Comment posted by Suprotim on Sunday, February 22, 2015 8:02 PM
@sachin The next articles in this series will be published this week.
Comment posted by bmoores on Saturday, March 14, 2015 4:52 PM
Any progress on the rest of this series?
Comment posted by Suprotim on Saturday, March 14, 2015 9:36 PM
@bmoores Sorry for the delay. The project had some bugs due to which we had to postpone the series. It should be released sometime after the 16th of this month. There are around 4 articles.
Comment posted by bmoores on Monday, March 16, 2015 4:13 PM
Thanks for the update and the work your doing for these articles. I am looking forward to them.
Comment posted by Nicolas Copin on Tuesday, March 17, 2015 5:15 AM
Great article ! Big thanks for it.
I can't wait for the part III !
Comment posted by Nicolas Copin on Tuesday, March 17, 2015 5:22 AM
Great article ! Big thanks for it.
I can't wait for the part III !
Comment posted by Neeraja Vajapeyajula on Wednesday, March 18, 2015 5:50 AM
Hai great article..its very useful and understandable by every one..
I am looking for next articles..Thanks
Comment posted by wakil on Saturday, April 25, 2015 8:25 AM
Its very good article on angular. Its one of the best i have seen. Thank you very much
Comment posted by Abbas on Thursday, May 7, 2015 12:29 PM
Hi great tutorial as a beginner i struggled with testing my ptemployees in browser address as shown above i keep getting 404 .0 error.
any ideas as i have followed your instruction to the .dot
Comment posted by Abbas on Thursday, May 7, 2015 4:18 PM
Hi great tutorial as a beginner i struggled with testing my ptemployees in browser address as shown above i keep getting 404 .0 error.
any ideas as i have followed your instruction to the .dot
Comment posted by chandan on Friday, May 15, 2015 6:07 AM
Install a Nuget package Microsoft.AspNet.WebApi.Cors.

If you are getting error for EnableCors function.
Comment posted by chandan kumar on Tuesday, May 19, 2015 2:35 AM
I donot find download link at github?

Any special steps to get the source code?
Comment posted by Jeff on Friday, May 22, 2015 12:37 PM
@@chandan The download link is working fine.