ASP.NET Core Controllers
Controllers are a core component of ASP.NET Core MVC (Model-View-Controller) applications. They handle incoming requests, process them, and return responses. This document explores how to create, configure, and use controllers effectively.
What are Controllers?
A controller is a class that:
- Inherits from
ControllerBase
orController
. - Contains public methods called action methods.
- Action methods handle specific HTTP requests and return an
IActionResult
.
Creating a Controller
To create a controller, you typically:
- Create a new C# class.
- Inherit from
Microsoft.AspNetCore.Mvc.ControllerBase
orMicrosoft.AspNetCore.Mvc.Controller
. - Add a public action method that returns an
IActionResult
. - Ensure the controller class name ends with "Controller" (e.g.,
HomeController
).
Example: A Simple Controller
using Microsoft.AspNetCore.Mvc;
namespace MyWebApp.Controllers
{
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAllProducts()
{
// In a real app, you'd fetch data from a database or service
var products = new[]
{
new { Id = 1, Name = "Laptop", Price = 1200.00 },
new { Id = 2, Name = "Mouse", Price = 25.00 }
};
return Ok(products); // Returns HTTP 200 OK with JSON data
}
[HttpGet("{id}")]
public IActionResult GetProductById(int id)
{
// Find product logic
if (id == 1)
{
return Ok(new { Id = 1, Name = "Laptop", Price = 1200.00 });
}
return NotFound(); // Returns HTTP 404 Not Found
}
[HttpPost]
public IActionResult CreateProduct([FromBody] Product newProduct)
{
if (newProduct == null)
{
return BadRequest();
}
// Save newProduct to database
return CreatedAtAction(nameof(GetProductById), new { id = newProduct.Id }, newProduct);
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
Routing to Controllers
ASP.NET Core uses a routing system to map incoming HTTP requests to controller actions. The most common ways to define routes are:
- Attribute Routing: Using attributes like
[Route]
,[HttpGet]
,[HttpPost]
, etc., directly on controllers and action methods. - Convention-Based Routing: Defined in the
Program.cs
(orStartup.cs
) file, which uses a URL pattern to match requests.
Attribute Routing Example
The [Route("api/[controller]")]
attribute on the controller means that all actions within this controller will be prefixed with /api/Products
. The [HttpGet("{id}")]
attribute on an action method specifies that this method handles GET requests to URLs like /api/Products/1
.
Action Methods
Action methods are public methods within a controller that handle requests. They must return an IActionResult
, which is an interface that represents the result of an action method. Common implementations include:
OkResult
(HTTP 200 OK)NotFoundResult
(HTTP 404 Not Found)BadRequestResult
(HTTP 400 Bad Request)CreatedAtActionResult
(HTTP 201 Created)JsonResult
(returns JSON data)ContentResult
(returns plain text)ViewResult
(for returning views in Razor Pages/MVC)
Action Method Parameters
Action methods can accept parameters. ASP.NET Core's model binder automatically tries to bind incoming request data (from query strings, route data, or request body) to these parameters.
[FromBody]
attribute for parameters that should be populated from the request body (typically for POST, PUT, and PATCH requests sending complex objects). Use [FromRoute]
, [FromQuery]
, or [FromHeader]
to explicitly specify the source of the parameter.
Controller Base Classes
ControllerBase
: The base class for controllers that don't render views. It provides essential MVC features, including action method support, model binding, and authorization. Ideal for API controllers.Controller
: Inherits fromControllerBase
and adds support for view rendering, making it suitable for traditional MVC applications that return HTML views.
Common Controller Scenarios
API Controllers
API controllers are typically used to build web APIs. They usually inherit from ControllerBase
and return data in formats like JSON or XML. The [ApiController]
attribute provides several convenient conventions for API development, such as automatic model validation and inferred binding from the request body.
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase
{
// ... actions
}
MVC Controllers
MVC controllers are used in applications that render HTML views. They inherit from Controller
and typically return ViewResult
, passing data to a Razor view.
public class HomeController : Controller
{
public IActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET Core MVC!";
return View(); // Renders Views/Home/Index.cshtml
}
}