Creating API controllers and defining endpoints are fundamental steps in building Web APIs with ASP.NET Core. They form the entry points through which clients interact with your API, enabling you to expose specific functionalities and data. This lesson will guide you through the process of creating controllers, defining actions (endpoints), and configuring routing to handle incoming HTTP requests.
An API controller in ASP.NET Core is a class that handles incoming HTTP requests and returns responses. It's the core component responsible for processing requests and orchestrating the logic required to fulfill them. Controllers are typically derived from the ControllerBase class, which provides access to various helper methods and properties for handling requests and responses.
The ControllerBase class offers several useful methods and properties:
Ok(): Creates an OkResult object, representing a successful HTTP 200 response.BadRequest(): Creates a BadRequestResult object, representing an HTTP 400 response indicating an invalid request.NotFound(): Creates a NotFoundResult object, representing an HTTP 404 response indicating that the requested resource was not found.CreatedAtAction(): Creates a CreatedAtActionResult object, representing an HTTP 201 response after successfully creating a new resource. It includes the URI of the newly created resource.StatusCode(): Creates a StatusCodeResult object, allowing you to specify any HTTP status code.Request: Provides access to the incoming HTTP request.HttpContext: Provides access to the current HTTP context.Here's a basic example of an API controller:
using Microsoft.AspNetCore.Mvc;
namespace MyWebApi.Controllers
{
[ApiController]
[Route("[controller]")] // This attribute defines the route for the controller
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
// Dummy data for demonstration
var products = new string[] { "Product 1", "Product 2", "Product 3" };
return Ok(products); // Returns a 200 OK response with the products
}
}
}
Explanation:
[ApiController]: This attribute indicates that the class is an API controller, enabling features like automatic model validation and attribute routing.[Route("[controller]")]: This attribute defines the route for the controller. [controller] is a token that gets replaced with the name of the controller (without the "Controller" suffix). In this case, the route will be /Products.GetProducts(): This is an action method that handles HTTP GET requests.IActionResult: This is the return type for action methods, allowing you to return different types of results (e.g., OkResult, NotFoundResult, BadRequestResult).