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.

Geckofx Browser in Winform Application

Bored with IE browser in your winform application ? Want to do everything as you doing in your Firefox or Chrome Browser ? Play with automation ? Then here is your choice . Introduction:  GeckoFX is a Windows Forms control written in clean, commented C# that embeds the Mozilla Gecko browser control in any Windows Forms Application. It also contains a simple class model providing access to the HTML and CSS DOM . GeckoFX was originally created by Andrew Young for the fast-growing visual CSS editor, Stylizer . It is now released as open-source under the Mozilla Public License.  You can download it here :   Geckofx 22.0 And the supporting file Xulrunner here :   Xulrunner Files Hope you have downloaded above two files. Here our journey going to start. Create your winform application in visual studio and do the following: right click the toolbox -> Choose items -> Browse the "Geckofx-winforms.dll" and click "yes" for “Load it anyw...

Code to create log files in C#.Net|Asp.Net

Introduction: In my previous article I have explained about how to create, delete and check whether the directory exists using C#.Net . In this article I am going to explain about  How to create log files in C#.Net. Explanation: Log files are useful to track any runtime errors and exceptions in all the applications. Below code will code will get the Message and Pagename as the input and creates the log file in that date. For that first i have imported below two namespaces.