Develop a REST solution in ASP.Net MVC

In this post we shall create a  Representational State Transfer Technology( REST) solution.

We are using Visual Studio 2017 for developing the application.

Create a new application

Then create a Core ASP.Net Application

Then select API

Allow for processing

The project open in Visual Studio 2017

The files open in Visual Studio.

Program.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace mvcrest
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup();
    }
}


ValuesController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace mvcrest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult Get(int id)
        {
            return "value";
        }

        // POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

Debug the project now.

The project in debug mode on the browser

 

Now, we will check up the methods in the controller one by one.

The default method is the

 // GET api/values
        [HttpGet]
        public ActionResult<IEnumerable> Get()
        {
            return new string[] { "value1", "value2" };
        }

This will be called via the default uri and will return a string array with two values “value1” and “value2”.

This is the browser screenshot for it.

Next method is

 // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult Get(int id)
        {
            return "value";
        }

The url is of type api/values/id where id is some integer. It returns “value”.

Here are two screenshots of using this url.

 

Now we will develop a controller that stores a list of books and returns from there.

Create a folder called Models in the project and then add a class called Book.

Add a class Book.

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

namespace mvcrest.Models
{
    public class Book
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }
}


Now, add a new Controller called BookController.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using mvcrest.Models;
namespace mvcrest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        // GET api/books
        [HttpGet]
        public Book[] Get()
        {
            return new Book[]
            {
        new Book
        {
            Id = 1,
            Name = "The Recursion Sutras"
        },
        new Book
        {
            Id = 2,
            Name = "WordPress Encyclopaedia"
        }
            };
        }
    }
}

Access the api/books url

 

Next step, we will create a Services folder and add a Repository.

Here is the code for the BookRepository class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using mvcrest.Models;
namespace mvcrest.Services
{
    public class BookRepository
    {
        public Book[] GetAllBooks()
        {
            return new Book[]
            {
        new Book
        {
            Id = 1,
            Name = "The Recursion Sutras"
        },
        new Book
        {
            Id = 2,
            Name = "WordPress Encyclopaedia"
        }
            };
        }
    }
}


We will use this class and its GetAllBooks method in the BookController class

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using mvcrest.Models;
using mvcrest.Services;
namespace mvcrest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private BookRepository repository;
        public BooksController()
        {
            repository = new BookRepository();
        }
        // GET api/books
        [HttpGet]
        public Book[] Get()
        {
            return repository.GetAllBooks();
        }
    }
}

It works.

 

 

Instead of the Book Array we can use an IEnumerable type which will make the system more generic.

Here is the modified code.

BookRepository

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using mvcrest.Models;
namespace mvcrest.Services
{
    public class BookRepository
    {
        private static Dictionary<int, Book> dict=new Dictionary<int,Book>();
        static BookRepository()
        {
            dict.Add(1, new Book
            {
                Id = 1,
                Name = "The Recursion Sutras"
            });
            dict.Add(2,

        new Book
        {
            Id = 2,
            Name = "WordPress Encyclopaedia"
        });
           
        }
        public IEnumerable GetAllBooks()
        {
        return dict.Values;
          
        }
    }
}


BookController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using mvcrest.Models;
using mvcrest.Services;
namespace mvcrest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private BookRepository repository;
        public BooksController()
        {
            repository = new BookRepository();
        }
        // GET api/books
        [HttpGet]
        public IEnumerable Get()
        {
            return repository.GetAllBooks();
        }
    }
}

The output remains the same.

 

Here is the final code

Book.cs

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

namespace mvcrest.Models
{
    public class Book
    {
        public int Id { get; set; }

        public string Name { get; set; }
    }
}

BookRepository.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using mvcrest.Models;
namespace mvcrest.Services
{
    public class BookRepository
    {
        private static Dictionary<int, Book> dict=new Dictionary<int,Book>();
        static BookRepository()
        {
            dict.Add(1, new Book
            {
                Id = 1,
                Name = "The Recursion Sutras"
            });
            dict.Add(2,

        new Book
        {
            Id = 2,
            Name = "WordPress Encyclopaedia"
        });
           
        }
        public IEnumerable GetAllBooks()
        {
        return dict.Values;
          
        }
        public Book GetBookById(int id)
        {

            Book book;
            bool found= dict.TryGetValue(id,out book);
            if (!found)
                return new Book {Id=0,Name="No Book" };
            else
                return book;

        }
        public string InsertBookById(string name)
        {

            
            int position = dict.Count+1;
            dict.Add(position, new Book {Id=position,Name=name });
            return "Inserted";

        }
        public string DeleteBookById(int id)
        {



            dict.Remove(id);
            return "Deleted";

        }
        public string UpdateBookById(int id,string name)
        {
            dict.Remove(id);
            dict.Add(id, new Book { Id = id, Name = name });
            return "Update Id " +id+ "Name "+name;
        }
    }
}

BookController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using mvcrest.Models;
using mvcrest.Services;
namespace mvcrest.Controllers
{
   // [Route("api/[controller]")]
    [ApiController]
    public class BooksController : ControllerBase
    {
        private BookRepository repository;
        public BooksController()
        {
            repository = new BookRepository();
        }
        // GET api/books
        [Route("api/books/names")]

        [HttpGet]
        public IEnumerable Get()
        {
           
            return repository.GetAllBooks();
        }
        // GET api/books/5
        [Route("api/books/search/{id}")]
       
        public  Book Search(int id)
        {
            return repository.GetBookById(id);
            
        }

        [Route("api/books/update/{id}/{name}")]

        public string Update(int id,string name)
        {
            return repository.UpdateBookById(id ,  name);

        }
        [Route("api/books/delete/{id}")]

        public string Delete(int id)
        {
            return repository.DeleteBookById(id);

        }
    }
}

Here are the output screen shots.

Search All

Search Book

Update

Search

Delete

Posted in: MVC

Leave a Reply