liveBook · Manning

Web API action method

As explained in Pro ASP.NET Core 7, Tenth Edition

A controller method that handles a matched request and contributes to producing its response.

A web API action method is a public method on a controller that handles a matched HTTP request. In a RESTful service, the request’s HTTP method and URL identify the operation. ASP.NET Core discovers controllers when the application starts and creates a controller instance when an action handles a request. section 19.4.2 section 19.6

Start with a controller such as ProductsController. ControllerBase gives its actions access to request-related properties, including Request, Response, RouteData, and ModelState. The controller is conventionally placed in a Controllers folder, but discovery does not require that location. Deriving from ControllerBase is also conventional rather than mandatory. section 19.4.2

Listing 19.6 The contents of the ProductsController.cs file in the Controllers folder
using Microsoft.AspNetCore.Mvc;
using WebApp.Models;

namespace WebApp.Controllers {

   [Route("api/[controller]")]
   public class ProductsController : ControllerBase {
       
       [HttpGet]
       public IEnumerable<Product> GetProducts() {
           return new Product[] {
               new Product() { Name = "Product #1" },
               new Product() { Name = "Product #2" },
           };
       }
               
       [HttpGet("{id}")]
       public Product GetProduct() {
           return new Product() {
               ProductId = 1, Name = "Test Product"
           };
       }
   }
}

The two GET actions show how a controller-level route and action-level HTTP attributes distinguish a product list from a single-product request. section 19.4.2

Build an action around the request it must accept:

  • Set the controller’s URL with [Route("api/[controller]")]. An [HttpGet] action handles GET api/products; [HttpGet("{id}")] adds a route segment for GET api/products/{id}. HTTP-method attributes also include HttpPost, HttpPut, HttpDelete, HttpPatch, and HttpHead. section 19.4.2
  • Declare parameters for request data. Model binding extracts values and supplies them to the action: a long id parameter, for example, receives the id from the matched URL. A [FromBody] Product parameter receives a posted product; [FromServices] can supply a service to an individual action. section 19.4.2
  • Use the bound data to do the work, then return the result. The product actions evolve from returning sample products to querying a DataContext; other actions accept POST, PUT, and DELETE requests to change stored products. section 19.4.2
Listing 19.8 Model binding in the ProductsController.cs file in the Controllers folder
using Microsoft.AspNetCore.Mvc;
using WebApp.Models;

namespace WebApp.Controllers {

    [Route("api/[controller]")]
    public class ProductsController : ControllerBase {
        private DataContext context;
                
        public ProductsController(DataContext ctx) {
            context = ctx;
        }
                
        [HttpGet]
        public IEnumerable<Product> GetProducts() {
            return context.Products;
        }
                
        [HttpGet("{id}")]
        public Product? GetProduct(long id,
                [FromServices] ILogger<ProductsController> logger) {
            logger.LogDebug("GetProduct Action Invoked");
            return context.Products.Find(id);
        }
    }
}

Here GetProduct accepts a bound route value, uses an injected logger, and looks up the requested product in the data context. section 19.4.2

Keep the action’s input deliberate. Accept only data the client should supply, and validate values produced by model binding. A validation action can also use [FromQuery] to accommodate differing query-parameter names sent by a controller view and a Razor Page. section 19.6 section 29.7.1

Check a product endpoint

Request GET api/products for the list, then GET api/products/2 for one product. To exercise a write action, send a JSON POST to http://localhost:5000/api/products using Invoke-RestMethod; PUT and DELETE requests exercise the corresponding update and delete actions. section 19.4.2

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Works through controller discovery, route and HTTP-method attributes, parameter binding, service access, and product operations; defers detailed validation treatment.
Examples
Uses product-list, product-lookup, and write actions, with Invoke-RestMethod requests against api/products.
What it assumes
Assumes C# methods and HTTP requests while introducing controller discovery, attributes, and model binding through code.
What you can do after
Build it from scratch as a controller action selected by URL and HTTP method, with bound inputs and a result.
How it connects
Connects controller routing, HTTP methods, model binding, dependency injection, data validation, and RESTful web services.

Also explained in

Compare how 4 books explain web API action method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.