Add a controller

A controller is a public class with one or more public methods known as actions. By convention, a controller is placed in the project root's Controllers directory. The actions are exposed as HTTP endpoints inside the web API controller.

Create a controller

  1. Select the Controllers folder in Visual Studio and add a new file called PizzaController.cs.

    An empty class file named PizzaController.cs is created in the Controllers directory. The directory name Controllers is a convention. The directory name comes from the model-view-controller architecture that the web API uses.

    Note: By convention, controller class names are suffixed with Controller.

  2. Add the following code to Controllers/PizzaController.cs. Save your changes.

    using ContosoPizza.Models;
    using ContosoPizza.Services;
    using Microsoft.AspNetCore.Mvc;
    
    namespace ContosoPizza.Controllers;
    
    [ApiController]
    [Route("[controller]")]
    public class PizzaController : ControllerBase
    {
        public PizzaController()
        {
        }
    
        // GET all action
    
        // GET by Id action
    
        // POST action
    
        // PUT action
    
        // DELETE action
    }

    Because this controller class is named PizzaController, this controller handles requests to https://localhost:{PORT}/pizza.

Get all pizzas

The first REST verb that you need to implement is GET, where a client can get all pizzas from the API. You can use the built-in [HttpGet] attribute to define a method that will return the pizzas from our service.

Replace the // GET all action comment in Controllers/PizzaController.cs with the following code:

[HttpGet]
public ActionResult<List<Pizza>> GetAll() =>
    PizzaService.GetAll();

The preceding action:

  • Responds only to the HTTP GET verb, as denoted by the [HttpGet] attribute.

  • Queries the service for all pizza and automatically returns data with a Content-Type value of application/json.

Retrieve a single pizza

The client might also want to request information about a specific pizza instead of the entire list. You can implement another GET action that requires an id parameter. You can use the built-in [HttpGet("{id}")] attribute to define a method that will return the pizzas from our service. The routing logic registers [HttpGet] (without id) and [HttpGet("{id}")] (with id) as two different routes. You can then write a separate action to retrieve a single item.

Replace the // GET by Id action comment in Controllers/PizzaController.cs with the following code:

[HttpGet("{id}")]
public ActionResult<Pizza> Get(int id)
{
    var pizza = PizzaService.Get(id);

    if(pizza == null)
        return NotFound();

    return pizza;
}

The preceding action:

  • Responds only to the HTTP GET verb, as denoted by the [HttpGet] attribute.

  • Requires that the id parameter's value is included in the URL segment after pizza/. Remember, the controller-level [Route] attribute defined the /pizza pattern.

  • Queries the database for a pizza that matches the provided id parameter.

Each ActionResult instance used in the preceding action is mapped to the corresponding HTTP status code in the following table:

ASP.NET Core action result

HTTP status code

Description

Ok is implied

200

A product that matches the provided id parameter exists in the in-memory cache. The product is included in the response body in the media type, as defined in the accept HTTP request header (JSON by default).

NotFound

404

A product that matches the provided id parameter doesn't exist in the in-memory cache.

Build and test the controller

Run the project in debug mode and test the API actions

You've now finished implementing the GET verbs. In the next unit, you can add more actions to PizzaController to support CRUD operations on pizza data.

Last updated