Follow by Email

Wednesday, February 19, 2014

Simple Example for ASP.NET WEB API in MVC 4 || Sample ASP.NET WEB API application

In this tutorial i will show how to develop a simple ASP.NET WEB API using MVC 4.

Asp.net Web Api is used to create http based services which can be consumed by large number of client devices or browsers or applications.

Example:

1. In Visual Studio --> go to new project --> empty mvc project

2. Right click on model and add a new class named EmployeeData.cs and define the model.

//Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication7.Models
{
    public class EmployeeData
    {
        public int EID { get; set; }
        public string EName { get; set; }
        public int ESalary { get; set; }
    }
}

3. Now Add a new controller Name EmployeeController and select Template
 Empty API Controller.



then define the controller and run the project.

//Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using MvcApplication7.Models;

namespace MvcApplication7.Controllers
{
    public class EmployeeController : ApiController
    {
        EmployeeData[] Emp = new EmployeeData[]
         {
             new EmployeeData { EID = 1, EName = "Emp 1", ESalary = 10 },
             new EmployeeData { EID = 2, EName = "Emp 2", ESalary = 100 },
             new EmployeeData { EID = 3, EName = "Emp 3", ESalary = 1000 },
         };

        public IEnumerable<EmployeeData> GetEmployees()
        {
            return Emp;
        }
    }
}


4. In the browser it may look like this:


 so the change the url as localhost:XXXX/api/Employee 

you will get the output as given below :