ASP.NET Core MVC Controllers
This document provides an in-depth guide to understanding and working with controllers in ASP.NET Core MVC applications. Controllers are a core component of the Model-View-Controller (MVC) architectural pattern, responsible for handling incoming requests, interacting with models, and selecting views to render.
What is a Controller?
In ASP.NET Core MVC, a controller is a class that:
- Handles incoming HTTP requests.
- Processes request data.
- Interacts with the application's data models.
- Selects a view to render the response.
Controller classes are typically placed in the Controllers
folder of your ASP.NET Core project.
Creating a Controller
A controller is simply a public class that inherits from Microsoft.AspNetCore.Mvc.Controller
. It's a convention to end controller class names with the suffix Controller
.
Example: A Simple Controller
using Microsoft.AspNetCore.Mvc;
namespace MyWebApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View(); // Renders the Index.cshtml view
}
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View(); // Renders the About.cshtml view
}
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View(); // Renders the Contact.cshtml view
}
}
}
Controller Actions
Public methods within a controller class are called actions. These methods are invoked by the routing system when a matching HTTP request is received. Action methods must return an object that implements the IActionResult
interface.
Common IActionResult Types
ViewResult
: Returns an HTML view.RedirectResult
: Redirects the browser to a different URL.ContentResult
: Returns plain text or HTML content.JsonResult
: Returns JSON data.StatusCodeResult
: Returns an HTTP status code.
Routing and Action Selection
ASP.NET Core uses a flexible routing system to map incoming URLs to specific controller actions. The default routing convention typically follows the pattern: /ControllerName/ActionName/OptionalParameters
.
For example, the URL /Home/About
would invoke the About
action on the HomeController
.
Route Constraints and Attributes
You can customize routing using route templates and attributes. For instance, applying the [Route]
attribute to a controller or action can define specific URL patterns.
[Route("api/[controller]/[action]")]
This attribute can be applied to a controller class to set a base route for all its actions. For example, a controller named ProductsController
would have routes like /api/Products/GetAll
.
[HttpGet]
, [HttpPost]
, etc.
HTTP verb attributes can restrict an action to specific HTTP methods. For example, [HttpGet("details/{id}")]
.
Passing Data to Views
Controllers can pass data to views using several mechanisms:
ViewData
: A dictionary-like object for passing small amounts of data.ViewBag
: A dynamic property that provides a more convenient way to accessViewData
.- Model Objects: Passing a strongly-typed model object to the view is the most common and recommended approach for complex data.
Example: Using ViewData and ViewBag
using Microsoft.AspNetCore.Mvc;
public class ProductController : Controller
{
public IActionResult Details(int id)
{
ViewData["ProductId"] = id;
ViewBag.ProductName = "Example Product";
// Fetch product details from a database or service
var product = new { Id = id, Name = "Example Product", Price = 19.99 };
return View(product); // Pass the product model to the view
}
}
Handling Request Data
Controllers can receive data from requests in various ways:
- Route Values: Data embedded in the URL.
- Query String Parameters: Data appended to the URL after a '?' (e.g.,
/search?q=aspnet
). - Form Data: Data submitted from an HTML form, typically via POST requests.
- Request Body: Data sent in the body of the request, common for APIs (e.g., JSON).
Model Binding
ASP.NET Core's model binder automatically maps incoming request data to parameters in your action methods or to properties of a model object passed to the action.
public IActionResult Search(string q, int page = 1)
Here, q
would be bound from the query string parameter ?q=...
, and page
would be bound from ?page=...
or use the default value of 1.
public IActionResult Create([FromBody] Product newProduct)
The [FromBody]
attribute instructs the model binder to read the request body, typically JSON, and deserialize it into the newProduct
object.
Controller Base Classes
While inheriting directly from Controller
is common, ASP.NET Core offers other base classes for specific scenarios:
ControllerBase
: Provides core MVC functionality without direct access toHttpContext.Session
orUser
, making it suitable for API controllers.PageModel
: Used with Razor Pages for page-specific logic.
Next Steps
Explore how to leverage controllers effectively in conjunction with models and views to build robust and maintainable web applications.