Introduction to ASP.NET Web Api

Introduction

ASP.NET Web API is a new framework for building and consuming web API’s. It’s a simple http service generally not soap, it uses simple http protocol. ASP.NET Web API is created on the top of .NET Framework that reaches a broad range of clients, including browsers and mobile devices. The WCF and the ASP.NET MVC development team together works and bring the brand new ASP.NET Web API.

intro

When we use ASP.NET web Api?

  • Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
  •  It also supports MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection.
  • Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

When I can Use WCF?

  •          Choose WCF when your framework are limited to .Net Framwork 3.5
  •          Choose WCF when you are working on SOAP based services

How to create a new Web Api project using Visual Studio 2010?

Here I am explaining you to step by step procedure for creating a simple ASP.NET Web API project.

Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project. From the Templates pane select ASP.NET MVC4 Web Application.

2

In the New ASP.NET MVC 4 Project dialog, select Web API and click OK.

3

Next i am going to create a sample application which loads a list of employees using ASP.NET Web Api and jQuery

First Add a new controller by right clicking the controller folder in your application like below.

4

Select template as Empty API Controller like below and click Add.

6

Add a new class library project by right clicking the solution and named it an Employee.Domain and create three folder named

Abstract, Repositories and Entities like below.

8

 

 

 

 

This project is responsible for storing all the business functionalities by using Repository Pattern.

Add new entity model class by right clicking Entities class named it as Employee.cs and the following properties.

namespace Employee.Domain.Entities

{
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
}

Add a new interface in this project by right clicking the Abstract folder and named it as IEmployeeRepository.cs and add a property like below.

using System.Collections.Generic;
namespace Employee.Domain.Abstract
{
public interface IEmployeeRepository
{
List<Entities.Employee> GetEmployees();
}
}

Add a concrete implementation class by right clicking the Repositories folder and named it as EmployeeRespository.cs and implement the above interface (IEmployeeRepository)

using System.Collections.Generic;
using System.Linq;
using Employee.Domain.Abstract;
namespace Employee.Domain.Repositories
{
public class EmployeeRepository:IEmployeeRepository
{
private readonly EmployeeDataContext _employeeDataContext;
public EmployeeRepository()
{
_employeeDataContext=new EmployeeDataContext();
}

//method for loading all the employees

public List<Entities.Employee> GetEmployees()
{
return _employeeDataContext.Employees.ToList();
}
}
}

Configuring EntityFramework 5.0.0

     To install EntityFramework, run the following command in the Package Manager Console

You can get the Package Manager Console from

9

Select the default project as Employee.Domain and Run the following command in this console.

Add new EmployeeDataContext class in Employee.Domain project and the following property

using System.Data.Entity;
namespace Employee.Domain
{
public class EmployeeDataContext:DbContext
{
public EmployeeDataContext(): base("name=EmployeeDataContext")
{
}
public DbSet<Entities.Employee> Employee { get; set; }
}
}

Create db ,named it as Company and create a new table

11

 

 

 

 

 

Setting connection string in web.config of web project and set the datasource of Company database like below.

<connectionStrings>

<add name=”EmployeeDataContext” connectionString=”Data Source=JAMEEL\SQLR2EXPRESS; Initial Catalog=Company; Integrated Security=True; MultipleActiveResultSets=True;Pooling=False;”

providerName=”System.Data.SqlClient” />

</connectionStrings>

Modify the Web Api configuration which is in the App_Start folder of the web project. In this I have add two custom routing for accessing the web api url by using and controller/action.

public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}

Next iam adding our web API method for loading all the employees in to the view. Add new action named GetEmployees in EmployeeController which is responsible for return Employees as Json.

public class EmployeeController : ApiController
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeController()
{
_employeeRepository=new EmployeeRepository();
}
public List<Employee.Domain.Entities.Employee>  GetEmployees()
{
return _employeeRepository.GetEmployees();
}
}

Next add new plain html page and load the Employee results as table structure by using jQuery.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml”&gt;

<head>

<title></title>

<script src=”Scripts/jquery-1.7.1.min.js” type=”text/javascript”></script>

<style type=”text/css”>

table, td, th
{
border: 1px solid green;
}
th
{
background-color: green;color: white;
}
</style>
</head>
<body>
<div id=”Employees”>
</div>
<script type=”text/javascript”>
$.getJSON(“/api/Employee/GetEmployees”, function (data) {
var table = “<table><tr><th>Name</th><th>Age</th><th>Address</th></tr>”;
var finalHtml = “”;
$.each(data, function (i, item) {
finalHtml = finalHtml + ‘<tr><td>’ + item.Name + ‘</td><td>’ + item.Age + ‘</td><td>’ + item.Address + ‘</td></tr>’;
});
table = table + finalHtml + ” </table>”;
$(‘#Employees’).html(table);
});
</script>
</body>
</html>

Hope you got a basic overview of WebApi and how to create a sample Web API and consuming by the client.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s