Sunday, 4 November 2018

Sample Way to Create ASP.Net MVC Web API


Sample Way to Create ASP.Net MVC Web API  

Step 1: Open the Visual Studio and click File → New → Project menu option.
A new Project dialog opens.

Step 2 − select Templates → Visual C# → Web.
Step 3 − select ASP.NET Web Application
Enter project name Web_API_Demo in the Name field and click Ok .

Step 4 − select the Empty option and check the Web API checkbox and click ok.
Step 5 − It will create a basic MVC project with minimal predefined content.
Step 6 − add a model. Right-click on the Models folder in the solution explorer and select Add → Class.


Step 7 − Select Class in the middle pan and enter Student.cs in the name field.
Step 8 − Add some properties for Student class using the following code.

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

namespace Demo_Web_API_.Models
{
    public class Student
    {
        public int RollNo { get; set; }
        public string Name { get; set; }
        public DateTime JoiningDate { get; set; }
        public string Course { get; set; }
    }
}
Step 9 − add the controller. Right-click on the controller folder in the solution explorer and select Add → Controller.



Step 10 − Select the Web API 2 Controller - Empty option. Then give Name As StudentsController (As below)
Step 11 − Click ‘Add’ button and the Add Controller dialog will appear.



Step 12 − Set the name to StudentsController and click ‘Add’ button.
using Demo_Web_API_.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Demo_Web_API_.Controllers
{
    public class StudentsController : ApiController
    {
        Student[] students = new Student[]{
         new Student { RollNo = 1, Name = "Ram", JoiningDate =DateTime.Parse(DateTime.Today.ToString()), Course = "MCA" },
         new Student { RollNo = 2, Name = "Sita", JoiningDate =DateTime.Parse(DateTime.Today.ToString()), Course = "BCA" },
         new Student { RollNo = 3, Name = "Mohan", JoiningDate =DateTime.Parse(DateTime.Today.ToString()), Course = "BBA" }
      };

        public IEnumerable<Student> GetAllStudents()
        {
            return students;
        }

        public IHttpActionResult GetStudent(int id)
        {
            var student = students.FirstOrDefault((p) => p.RollNo == id);
            if (student == null)
            {
                return NotFound();
            }
            return Ok(student);
        }
    }
}

Step 13 − Run this application and add at the end of URL /api/Students/ then  press ‘Enter’. You will get below output.





Step 14 − Use this URL http://localhost:63457/api/Students/1 to get following output