Apr 19, 2016

How to create RESTful API with MVC 6 and Asp.Net Core 1.0

Going to create RESTful API using ASP.NET Core 1.0 or MVC 6. I assume, you know the RESTful API so I am not going to explain what is the RESTful Service / API in this article.

We are talking about MVC 6 and Asp.Net core 1.0. just for your information if you don’t know that like MVC 6 is a part of Asp.Net core 1.0 and it is a completely new unified framework for writing server side web applications and APIs.

One of the changes in MVC 6 is a separation of Asp.Net MVC  and Web API is now past and merge into one. I thought it is good to having a look what changed has made to creating a RESTful API in MVC 6.

Let's start with simple CRUD (Create, Read, Update, Delete) operation in MVC 6 API.

Following  below steps to create RESTful API in MVC 6 with Visual Studio 2015.

Step 1: Create a new project using visual Studio 2015.
  - Open Visual Studio 2015 and go to file section and select New Project.

Step 2: Here you can choose ASP.NET 5 templates.


  - As I already mention MVC 6 has removed the separation of web controller and API controller and combine into one. So it's no matter which application you choose.
  - Yes, If you have a specific requirement like just want to create RESTful API then also ASP.NET 5 templates fulfill your requirement.

Step 3: Once solution created, you will notice few new things come up with default solution and few things have been removed.

  • App_Data, App_Start and Global.asax have been removed.
  • New *.Json file have been added.
  • Added new folders wwwroot and Dependencies
 Step 4: Build the solution and restore the packages during the build process.
  -  Please check output window for build process and check solution has built successfully.

Step 5: You need to add Model for this exercise which is a Student.
  - Student Model have following property
        a. StudentId
        b. Name
        c. SurName


using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace RESTfulAPI.Models
{
    public class Student
    {
        public int StudentId { get; set; }
        public string Name { get; set; }
        public string SurName { get; set; }
    }
}


Step 6: Now create a new controller for Student API, Select API Controller.


Write controller name as per your requirement.

 

Step 7: Once added API controller. You will get ready API controller.
  - MVC 6 and Visual Studio 2015 provide the scaffolding of RESTful API.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Mvc;
using Microsoft.Data.Entity;
using RESTfulAPI.Models;

namespace RESTfulAPI.Controllers
{
    [Produces("application/json")]
    [Route("api/Students")]
    public class StudentsController : Controller
    {
        private ApplicationDbContext _context;

        public StudentsController(ApplicationDbContext context)
        {
            _context = context;
        }

        // GET: api/Students
        [HttpGet]
        public IEnumerable GetStudent()
        {
            return _context.Student;
        }

        // GET: api/Students/5
        [HttpGet("{id}", Name = "GetStudent")]
        public async Task GetStudent([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            Student student = await _context.Student.SingleAsync(m => m.StudentId == id);

            if (student == null)
            {
                return HttpNotFound();
            }

            return Ok(student);
        }

        // PUT: api/Students/5
        [HttpPut("{id}")]
        public async Task PutStudent([FromRoute] int id, [FromBody] Student student)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            if (id != student.StudentId)
            {
                return HttpBadRequest();
            }

            _context.Entry(student).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(id))
                {
                    return HttpNotFound();
                }
                else
                {
                    throw;
                }
            }

            return new HttpStatusCodeResult(StatusCodes.Status204NoContent);
        }

        // POST: api/Students
        [HttpPost]
        public async Task PostStudent([FromBody] Student student)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            _context.Student.Add(student);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (StudentExists(student.StudentId))
                {
                    return new HttpStatusCodeResult(StatusCodes.Status409Conflict);
                }
                else
                {
                    throw;
                }
            }

            return CreatedAtRoute("GetStudent", new { id = student.StudentId }, student);
        }

        // DELETE: api/Students/5
        [HttpDelete("{id}")]
        public async Task DeleteStudent([FromRoute] int id)
        {
            if (!ModelState.IsValid)
            {
                return HttpBadRequest(ModelState);
            }

            Student student = await _context.Student.SingleAsync(m => m.StudentId == id);
            if (student == null)
            {
                return HttpNotFound();
            }

            _context.Student.Remove(student);
            await _context.SaveChangesAsync();

            return Ok(student);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                _context.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool StudentExists(int id)
        {
            return _context.Student.Count(e => e.StudentId == id) > 0;
        }
    }
}




Step 8: Now time to access RESTful API from POSTMAN.
- You can consume RESTful API from any source and get the result.

Hope this will help you to create your first RESTful API using MVC 6 and ASP.NET Core 1.0.

No comments:

Post a Comment