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

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# Extension Methods Example

In this article i am going to explain about Extension Methods  with example. Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. If you do implement extension methods for a given type, remember the following points: An extension method will never be called if it has the same signature as a method defined in the type. Extension methods are brought into scope at the namespace level. For example, if you have multiple static classes that contain extension methods in a single namespace named Extensions, they will all be brought into scope by the using Extensions; directive. ...

VBScript equivalent string functions in C#.Net

C# Method VBScript Description IndexOf() InStr Returns the position of the first occurrence of one string within another. The search begins at the first character of the string - InStrRev Returns the position of the first occurrence of one string within another. The search begins at the last character of the string ToLower() LCase Converts a specified string to lowercase SubString() Left Returns a specified number of characters from the left side of a string Length() Len Returns the number of characters in a string TrimStart() LTrim Removes spaces on the left side of a string TrimEnd() RTrim Removes spaces on the right side of a string Trim() Trim Removes spaces on both the left and the right side of a string SubString() M...