How to create your first WEB API Project in ASP.Net MVC

By
Advertisement
In this tutorial i am going to explain about how to create Web API Project in asp.net


1. Start the visual studio and from the file menu select the new project. From the installed templates select web and Select the ASP.Net Web Application Projet template. Select the appropriate Location and Enter the suitable name for your web api(here it is WebApiDemo) .And then click Ok to continue as shown in figure.

Step 1 of How to create your first WEB API Project in ASP.Net MVC

2. In this step Select Empty template and also check Web API option in Add folders and core references for option and then click ok to continue as shown in the below image.

Step 2 of How to create your first WEB API Project in ASP.Net MVC

3. Once the second step is completed then the project will get loaded. Right click the Models folder and then select Add then select Class. Name the class as Employee.cs

Step 3 of How to create your first WEB API Project in ASP.Net MVC

4. Add the following properties in the Employee.cs file.

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

namespace WebApiDemo.Models
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string EmployeeName { get; set; }
        public string Department { get; set; }
        public string Designation { get; set; }
    }
}

5. Once the step 4 is completed now i will show you how to add the controller to the web api project. Now right click the controller folder and then select add then select controller as shown in below.

Step 5 of How to create your first WEB API Project in ASP.Net MVC
6.In this step select Web API 2 Controller - Empty option from the Add Scaffold Menu

Step 6 of How to create your first WEB API Project in ASP.Net MVC

It is not necessary to put your contollers into a folder named Controllers. The folder name is just a convenient way to organize your source files.

7.In the Add Controller dialog, name the controller "EmployeeController". Click Add.

Step 7 of How to create your first WEB API Project in ASP.Net MVC

8.Replace the code in this file with the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApiDemo.Models;

namespace WebApiDemo.Controllers
{
    public class EmployeeController : ApiController
    {
       
        Employee[] employees = new Employee[]
        {
            new Employee { EmployeeId = 1, EmployeeName = "Kannadasan", Department = "Development", Designation = "Development Lead" },
            new Employee { EmployeeId = 2, EmployeeName = "Kaviyarasan", Department = "Quality Control", Designation = "Quality Lead" },
            new Employee { EmployeeId = 3, EmployeeName = "Xavier", Department = "Development", Designation = "Tech Lead" },
            new Employee { EmployeeId = 4, EmployeeName = "Ramkumar", Department = "Design", Designation = "Design Lead" }
        };

        public IEnumerable<Employee> GetAllEmployees()
        {
            return employees;
        }

        public IHttpActionResult GetEmployee(int id)
        {
            var employee = employees.FirstOrDefault((p) => p.EmployeeId == id);
            if (employee == null)
            {
                return NotFound();
            }
            return Ok(employee);
        }
    }
}

That's it. Your first Web API Project is ready.Now if you run the project and hit the url http://localhost:43152/api/employee . (Change the port no - 43152 as per your project. If you run the project you will know the allocated port number for your project)

By default the output will be in XML Format as shown below.
Output of How to create your first WEB API Project in ASP.Net MVC

If you need the output in the json format then in the WebApiConfig.cs file in the App_Start folder include the System.Net.Http.Headers namespace after installing the nuget package (Install-Package Microsoft.Net.Http) and change the code like below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Net.Http.Headers;

namespace WebApiDemo
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            //For json output
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

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


Now the output will look like below.
JSON output of How to create your first WEB API Project in ASP.Net MVC

Hope you have enjoyed. Please share your comments and share this article.. Happy coding...

0 comments:

Post a Comment

Online Casino