Exercise: ASP.
NET Core Web API and Routing – Library System
You are tasked with building a Web API for managing books in a library. Apply all the
routing concepts we covered (attribute routing, tokens, HTTP verbs, route constraints,
etc.).
Requirements
Controller Setup
• Create a controller named BooksController.
• Use [ApiController] and [Route("api/[controller]")].
Get All Books
• Implement an action GetAllBooks() using [HttpGet].
• Should return a list of book titles ("Harry Potter", "Lord of the Rings", "C#
Programming").
• Request Example: GET /api/books
Get Book by ID
• Implement an action GetBook(int id) using [HttpGet("{id:int}")].
• Should return "Book {id}".
• Request Example: GET /api/books/2 → "Book 2"
Get Book by Title
• Implement an action GetBookByTitle(string title) using
[HttpGet("title/{title:alpha}")].
• Should return "Book titled {title}".
• Request Example: GET /api/books/title/HarryPotter → "Book titled HarryPotter"
Add a New Book
• Implement an action AddBook([FromBody] string book) using [HttpPost].
• Should return "Book {book} added".
• Request Example: POST /api/books with body "The Hobbit"
Update a Book
• Implement an action UpdateBook(int id, [FromBody] string book) using
[HttpPut("{id:int}")].
• Should return "Book {id} updated to {book}".
• Request Example: PUT /api/books/3 with body "Game of Thrones"
Delete a Book
• Implement an action DeleteBook(int id) using [HttpDelete("{id:int}")].
• Should return "Book {id} deleted".
• Request Example: DELETE /api/books/4
Bonus Challenge
• Use [HttpGet("details/{id:int}/{title:alpha}")] to return a combined response like:
"Book {id} is titled {title}"
• Request Example: GET /api/books/details/5/Programming → "Book 5 is titled
Programming"
Deliverables:
• Write the full BooksController code with all required actions.
• Test using Swagger or Postman to ensure all routes work as expected.
Exam Style
Exam Question: [Link] Core Web API – Library System
You are tasked with developing a Web API to manage books in a library. The API should
allow users to:
1. Retrieve a list of all books.
2. Retrieve details of a specific book by its ID.
3. Search for a book by its title.
4. Add a new book to the library.
5. Update the title of an existing book.
6. Delete a book from the library.
7. Retrieve both the ID and title of a book in a single request.
Requirements:
• Implement a controller named BooksController.
• Use attribute routing to define endpoints.
• Apply appropriate HTTP verbs for each operation.
• Use route constraints where necessary to validate input.
• Test your API to ensure that all routes work as intended.
Instructions:
• Write the full BooksController code with all necessary methods.
• Do not include any extra functionality beyond what is described.