What is Asp.Net Web API?
Asp.Net Web API is a framework for building HTTP services that can be consumed by a broad range of clients including browsers, mobiles, iphone and tablets. It is very similar to ASP.NET MVC since it contains the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection. But it is not a part of the MVC Framework. It is a part of the core ASP.NET platform and can be used with MVC and other types of Web applications like Asp.Net WebForms. It can also be used as an stand-alone Web services application.
ASP.NET Web API was previously called as WCF Web API and recently merged into ASP.NET MVC 4 beta. The ASP.NET Web API comes with its own controller called ApiController. So now we got two types of controllers while developing MVC applications: one is the default MVC Controller and the other one is the ApiController. Choosing the right controller for the right job is important. For creating REST services we have to use the ApiController, basically these controllers return data. For returning views (aspx, cshtml) we have to use the default controller. In our sample we are going to create a service that returns only data and hence we go with ApiController. So let us create an restful service using Web API repository pattern .
Step 1: Let’s create a new ASP.NET MVC 4 web application.
Step 2: Select an empty template
The solution contains lot of things that we don’t require for creating a service like Content,Scripts, Views etc.
Step 3: In Global.asax.cs, there will be already two routes defined: one is for the mvc controller and the other one for the api controller.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id =
UrlParameter.Optional }
);
}
Since we are going to create a service that will return only data, remove the mvc controller’s route and modify the other accordingly.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Step 4: Next thing we have to do is create the model Employee.
public class Employee
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string Designation { get; set; }
public DateTime EMailId { get; set; }
}
Step 5: Create a controller that exposes methods. The "Add Controller" window displays different useful scaffolding options but I’m interested on the "API Controller with empty read/write actions".
public class EmployeesController : ApiController
{
// GET /api/employees
public IEnumerable
{
return new string[] { "value1", "value2" };
}
// GET /api/employees/5
public string Get(int id)
{
return "value";
}
// POST /api/employees
public void Post(string value)
{
}
// PUT /api/employees/5
public void Put(int id, string value)
{
}
// DELETE /api/employees/5
public void Delete(int id)
{
}
}
If you notice our EmployeesController it is derived from the new ApiController. The controller contains methods to get all the employees, get a emplyee by Id, create new employee, edit a employee and delete a employee. Any method starts with Get is automatically mapped with the HTTP GET method, any method that starts with Post is automatically mapped with the HTTP POST method and so on.
public class EmployeesController : ApiController
{
public IEnumerable
{
throw new NotImplementedException();
}
public Employees Get(int id)
{
throw new NotImplementedException();
}
public HttpResponseMessage
{
throw new NotImplementedException();
}
public Employees Put(Employees employee)
{
throw new NotImplementedException();
}
public HttpResponseMessage Delete(int id)
{
throw new NotImplementedException();
}
}
Step 6: Create an IEmployeesRepository interface repository as we are using the repository pattern
public interface IEmployeesRepository
{
IEnumerable
Employees Get(int id);
Employees Post(Employees employees);
Employees Put(Employees employees);
bool Delete(int id);
}
Step 7: Implement IEmployeesRepository methods in EmployeeRepository.cs class file
public class EmployeesRepository : IEmployeesRepository
{
private
static
SampleDBEntities dataContext = new
SampleDBEntities();
public static List
{
var query = from employee in dataContext.Employees
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
{
dataContext.Employees.Add(e);
dataContext.SaveChanges();
return GetAllEmployees();
}
public static List
{
var emp = (from employee in dataContext.Employees
where employee.EmployeeID == e.EmployeeID
select employee).SingleOrDefault();
emp.EmployeeName = e.EmployeeName;
emp.Designation = e.Designation;
emp.EMailID = e.EMailID;
dataContext.SaveChanges();
return GetAllEmployees();
}
public static List
{
var emp = (from employee in dataContext.Employees
where employee.EmployeeID == e.EmployeeID
select employee).SingleOrDefault();
dataContext.Employees.Remove(emp);
dataContext.SaveChanges();
return GetAllEmployees();
}
}
Step 8: In Employees controller inject your IEmployeesRepository interface in the controller instance.
public class EmployeesController : ApiController
{
private readonly IEmployeesRepository _employeeRepository;
public EmployeesController(IEmployeesRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
// GET api/employees
[Route("api/employees")]
public
HttpResponseMessage Get()
{
var employees= _
employeeRepository.GetAllEmployees();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
return
response;
}
// GET api/employees/5
[Route("api/ptemployees/{id?}")]
public
HttpResponseMessage Get(int
id)
{
var employees =
_employeeRepository.GetEmployee(id);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
return
response;
}
[Route("api/employees/{name}")]
public
HttpResponseMessage Get(string
name)
{
var employees =
_employeeRepository.SearchEmployeesByName(name);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
return
response;
}
[Route("api/employees")]
public
HttpResponseMessage Post(Employee e)
{
var employees =
_employeeRepository.InsertEmployee(e);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
return
response;
}
[Route("api/employees")]
public
HttpResponseMessage Put(Employee e)
{
var employees =
_employeeRepository.UpdateEmployee(e);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
return
response;
}
[Route("api/employees")]
public
HttpResponseMessage Delete(Employee e)
{
var employees =
_employeeRepository.DeleteEmployee(e);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, employees);
return
response;
}
}
Our service is ready to be exposed to the client and can be hosted in IIS or through Self-Hosting.