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:

Creating a Controller

To create a controller, you typically:

  1. Create a new C# class.
  2. Inherit from Microsoft.AspNetCore.Mvc.ControllerBase or Microsoft.AspNetCore.Mvc.Controller.
  3. Add a public action method that returns an IActionResult.
  4. 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 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:

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.

Tip: Use [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

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
    }
}
            

Further Reading

Next: Routing