ControllerBase is a common base class for ASP.NET Core MVC controllers. It gives actions access to the current request and provides helper methods for choosing HTTP responses. In a RESTful controller, it is useful when returning a product should produce a different response from reporting that the product does not exist. section 19.4.2 section 19.5.3
A public class named ProductsController is discovered as a controller, and its public methods are actions. Deriving from ControllerBase is conventional, not required for discovery. A new controller instance is created when an action handles a request, so its request-related properties describe that request. 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 ProductsController listing shows the base class alongside the route and HTTP-method attributes: GET /api/products selects GetProducts; GET /api/products/{id} selects GetProduct. section 19.4.2
Useful properties expose request-processing state:
- HttpContext, Request, and Response provide the current request context, HTTP request, and HTTP response. section 19.4.2
- RouteData contains data extracted from the URL; ModelState holds validation details; User describes the associated user. section 19.4.2
Actions can return data directly. Returning an object has the same effect as passing it to Ok and returning the result; returning null has the same effect as NoContent. To select a response explicitly, return an IActionResult created by a ControllerBase helper rather than writing directly to HttpResponse. section 19.5.3
Make a missing product a 404
For GET /api/products/{id}, an action returning a missing product as null yields 204 No Content by default. Instead, return Task<IActionResult>, look up the product, and return NotFound() when it is null or Ok(product) when found. A request for /api/products/1000 can then receive 404 Not Found rather than 204. section 19.5.3
Table 19.7 Useful ControllerBase action result methods (view table figure)
| Name |
Description |
|---|---|
| Ok |
The IActionResult returned by this method produces a 200 OK status code and sends an optional data object in the response body. |
| NoContent |
The IActionResult returned by this method produces a 204 NO CONTENT status code. |
| BadRequest |
The IActionResult returned by this method produces a 400 BAD REQUEST status code. The method accepts an optional model state object that describes the problem to the client, as demonstrated in the "Validating Data" section. |
| File |
The IActionResult returned by this method produces a 200 OK response, sets the Content-Type header to the specified type, and sends the specified file to the client. |
| NotFound |
The IActionResult returned by this method produces a 404 NOT FOUND status code. |
| Redirect RedirectPermanent |
The IActionResult returned by these methods redirects the client to a specified URL. |
| RedirectToRoute RedirectToRoutePermanent |
The IActionResult returned by these methods redirects the client to the specified URL that is created using the routing system, using convention routing, as described in the "Redirecting Using Route Values" sidebar. |
| LocalRedirect LocalRedirectPermanent |
The IActionResult returned by these methods redirects the client to the specified URL that is local to the application. |
| RedirectToAction RedirectToActionPermanent |
The IActionResult returned by these methods redirects the client to an action method. The URL for the redirection is created using the URL routing system. |
| RedirectToPage RedirectToPagePermanent |
The IActionResult returned by these methods redirects the client to a Razor Page, described in chapter 23. |
| StatusCode |
The IActionResult returned by this method produces a response with a specific status code. |
The helper-method table distinguishes Ok, NoContent, BadRequest, File, and NotFound by the responses they produce; it also lists redirection helpers. section 19.5.3
These helpers are not limited to success and errors. Redirect("/api/products/1") redirects to a URL; RedirectToAction can target an action and route values, while RedirectToRoute can supply route values directly. Choose the result that matches the response the client should receive. section 19.5.3

