Create New Project

Template: ASP.NET Core Web API

Framework: .NET 6.0

Check “Configure for HTTPS

Check “Use controllers (uncheck to use minimal API)” for controller vs minimal API

Check “Enable OpenAPI support” for Swagger OpenAPI support

Book Class

    public class Book
    {

        public int BookID { get; set; }
        public string Title { get; set; }

        public int Year { get; set; }
        public long ISBN { get; set; }
        public DateTime PublishedDate { get; set; }
        public short Price { get; set; }

        public int AuthorID { get; set; }
    }

Book Controller

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace TestWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BookController : ControllerBase
    {
        private static List<Book> books = new List<Book> { new Book { BookID = 100, Title = "Book 100" }, new Book { BookID = 101, Title = "Book 101" } };

        [HttpGet]
        public async Task<ActionResult<List<Book>>> Get()
        {           
            return Ok(books);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Book>> Get(int id)
        {

            var book = books.Find( a => a.BookID == id );

            if (book == null)
                return BadRequest("Book not found.");

            return Ok(book);
        }

        [HttpPost]
        public async Task<ActionResult<List<Book>>> Add(Book book)
        {
            books.Add(book);
            return Ok(books);
        }

        [HttpPut]
        public async Task<ActionResult<List<Book>>> Update(Book request)
        {
            var book = books.Find(a => a.BookID == request.BookID);

            if (book == null)
                return BadRequest("Book not found.");

            book.Title = request.Title;

            return Ok(books);
        }

        [HttpDelete("{id}")]
        public async Task<ActionResult<List<Book>>> Delete(int id)
        {
            var book = books.Find(a => a.BookID == id);

            if (book == null)
                return BadRequest("Book not found.");

            books.Remove(book);

            return Ok(books);
        }
    }
}

or … For Delete, pass in object instead of id.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace TestWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BookController : ControllerBase
    {
        private static List<Book> books = new List<Book> { new Book { BookID = 100, Title = "Book 100" }, new Book { BookID = 101, Title = "Book 101" } };

        [HttpGet]
        public async Task<ActionResult<List<Book>>> Get()
        {           
            return Ok(books);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Book>> Get(int id)
        {

            var book = books.Find( a => a.BookID == id );

            if (book == null)
                return BadRequest("Book not found.");

            return Ok(book);
        }

        [HttpPost]
        public async Task<ActionResult<List<Book>>> Add(Book book)
        {
            books.Add(book);
            return Ok(books);
        }

        [HttpPut]
        public async Task<ActionResult<List<Book>>> Update(Book book)
        {
            var bookSelected = books.Find(a => a.BookID == book.BookID);

            if (bookSelected == null)
                return BadRequest("Book not found.");

            bookSelected.Title = book.Title;

            return Ok(books);
        }

        [HttpDelete]
        public async Task<ActionResult<List<Book>>> Delete(Book book)
        {
            var bookSelected = books.Find(a => a.BookID == book.BookID);

            if (bookSelected == null)
                return BadRequest("Book not found.");

            books.Remove(bookSelected);

            return Ok(books);
        }
    }
}

BookController using Entity Framework

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace TestWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class BookController : ControllerBase
    {
        //private static List<Book> books = new List<Book> { new Book { BookID = 100, Title = "Book 100" }, new Book { BookID = 101, Title = "Book 101" } };

        private readonly DataContext _context;

        public BookController(DataContext context)
        {
            _context = context;
        }

        [HttpGet]
        public async Task<ActionResult<List<Book>>> Get()
        {           
            //return Ok(books);
            return Ok(await _context.books.ToListAsync());
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Book>> Get(int id)
        {

            //var book = books.Find( a => a.BookID == id );
            var book = await _context.books.FindAsync(id);  // Find by Primary Key (BookId)

            if (book == null)
                return BadRequest("Book not found.");

            return Ok(book);
        }

        [HttpPost]
        public async Task<ActionResult<List<Book>>> Add(Book book)
        {
            //books.Add(book);
            _context.books.Add(book);
            await _context.SaveChangesAsync();

            return Ok(await _context.books.ToListAsync());
        }

        [HttpPut]
        public async Task<ActionResult<List<Book>>> Update(Book book)
        {
            //var bookSelected = books.Find(a => a.BookID == book.BookID);
            var bookSelected = await _context.books.FindAsync(book.BookID); // Find by Primary Key (BookId)

            if (bookSelected == null)
                return BadRequest("Book not found."); 

            bookSelected.Title = book.Title;

            await _context.SaveChangesAsync();

            return Ok(await _context.books.ToListAsync());
        }

        [HttpDelete]
        public async Task<ActionResult<List<Book>>> Delete(Book book)
        {
            //var bookSelected = books.Find(a => a.BookID == book.BookID);
            var bookSelected = await _context.books.FindAsync(book.BookID); // Find by Primary Key (BookId)

            if (bookSelected == null)
                return BadRequest("Book not found.");

            //books.Remove(bookSelected);
            _context.books.Remove(bookSelected);

            await _context.SaveChangesAsync();

            return Ok(await _context.books.ToListAsync());
        }
    }
}

Example:

Last modified: April 17, 2022

Author

Comments

Write a Reply or Comment