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:
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:
Now add a new item into our ProjectTrackingServices. Choose Data section and then choose ADO.NET 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
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:
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:
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)
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
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