Skip to main content

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

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...

Comments

Popular posts from this blog

Sort Dictionary Based On Value In Asp.Net And C#.Net | Convert Dictionary into KeyValuePair or KeyValuePair into Dictionary.

In this tutorial i am going to explain about how to sort dictionary object based on value in asp.net and C#.Net or convert unsorted dictionary to sorted dictionary object in C#.Net and VB.Net or Convert Dictionary into KeyValuePair or KeyValuePair into Dictionary.

Code To Convert rupees(numbers) into words using C#.Net

Introduction: In my previous article I have explained about how to validate emailid using javascript . In this article I am going to explain about code used to convert rupees(numbers) into words using C#.Net . Explanation: For explanation purpose I have a page. It has a textbox to input the numbers. And when you click on the convert to words button then it will convert the input numbers into words and shows it in the below label. Below is the C# code used to do this functionality. public static string NumbersToWords( int inputNumber) {     int inputNo = inputNumber;     if (inputNo == 0)         return "Zero" ;     int [] numbers = new int [4];     int first = 0;     int u, h, t;     System.Text. StringBuilder sb = new System.Text. StringBuilder ();     if (inputNo < 0)     { ...

C# code to send mail using smtp from gmail,yahoo mail and live mail

Introduction: In my previous article I have explained about   How to bind/Unbind events in jQuery . In this article I am going to explain about how to send mail from ASP.Net using gmail,yahoomail and live mail credentials. Explanation: First Include the below namespaces in your code behind file. using System; using System.Net; using System.Net.Mail;