Controllers in ASP.NET Core
Controllers are a fundamental part of building web applications with ASP.NET Core MVC. They act as the central point for handling incoming browser requests, interacting with models for data, and selecting views to render the response.
What is a Controller?
A controller is a class that contains public methods called action methods. Each action method typically handles a specific HTTP request and is responsible for:
- Receiving input from the user (e.g., form data, query strings, route parameters).
- Interacting with the application's models to retrieve or manipulate data.
- Returning a result to the browser, usually by rendering a view or returning data in a format like JSON.
Creating a Controller
In ASP.NET Core MVC, controllers are typically placed in a Controllers
folder in your project. A controller class is a plain C# class that inherits from Microsoft.AspNetCore.Mvc.Controller
.
Here's a simple example of a controller:
using Microsoft.AspNetCore.Mvc;
namespace MyWebApp.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
// This action method handles requests to the "/" URL
ViewData["Message"] = "Welcome to ASP.NET Core!";
return View(); // Renders the Index.cshtml view
}
public IActionResult About()
{
// This action method handles requests to "/Home/About"
ViewData["Message"] = "Your application description page.";
return View(); // Renders the About.cshtml view
}
public IActionResult Contact()
{
// This action method handles requests to "/Home/Contact"
ViewData["Message"] = "Your contact page.";
return View(); // Renders the Contact.cshtml view
}
}
}
Action Methods
Action methods are public methods within a controller that return an IActionResult
. The IActionResult
interface represents the result of an action method, allowing for various types of responses.
ViewResult
: Used to render an HTML view.JsonResult
: Used to return JSON data, common for API endpoints.ContentResult
: Used to return plain text.RedirectResult
: Used to redirect the browser to another URL.StatusCodeResult
: Used to return an HTTP status code.
Example: Action Method Returning JSON
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using MyWebApp.Models; // Assuming you have a Product model
namespace MyWebApp.Controllers
{
public class ProductsController : Controller
{
public IActionResult GetProducts()
{
var products = new List<Product>
{
new Product { Id = 1, Name = "Laptop", Price = 1200.00m },
new Product { Id = 2, Name = "Keyboard", Price = 75.50m },
new Product { Id = 3, Name = "Mouse", Price = 25.00m }
};
// Returns a JSON representation of the product list
return Json(products);
}
}
}
Routing to Controllers
ASP.NET Core uses a routing system to map incoming URLs to specific action methods within controllers. By default, the routing convention is /ControllerName/ActionName/OptionalParameters
.
For example, the Index
action in the HomeController
can be accessed via /Home/Index
or, if it's the default action for the controller, simply /Home
. The Index
action in the root controller (often HomeController
) can be accessed via /
.
Model Binding
Model binding is a powerful feature that automatically maps incoming request data (from query strings, form posts, route data, etc.) to parameters of your action methods or to model objects.
Example: Model Binding with a Parameter
using Microsoft.AspNetCore.Mvc;
namespace MyWebApp.Controllers
{
public class ProductsController : Controller
{
public IActionResult Details(int id)
{
// The 'id' parameter is automatically populated from the URL segment
// e.g., /Products/Details/5 will set 'id' to 5
if (id <= 0)
{
return NotFound(); // Returns a 404 Not Found result
}
// Logic to retrieve product with the given 'id'
var product = GetProductById(id);
if (product == null)
{
return NotFound();
}
return View(product); // Passes the product to the Details.cshtml view
}
private Product GetProductById(int id) { /* ... */ return null; } // Placeholder
public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } } // Placeholder
}
}
Example: Model Binding with a Complex Type
You can also bind to complex model types directly:
using Microsoft.AspNetCore.Mvc;
using MyWebApp.Models; // Assuming you have a UserRegistration model
namespace MyWebApp.Controllers
{
public class AccountController : Controller
{
[HttpPost] // Specifies this action responds to POST requests
public IActionResult Register(UserRegistration model)
{
if (ModelState.IsValid)
{
// Process the valid registration data
// ...
return RedirectToAction("Success");
}
// If model is not valid, redisplay the registration form
return View(model);
}
}
}
Controller Actions and HTTP Verbs
You can explicitly specify which HTTP verbs an action method should respond to using attributes like [HttpGet]
, [HttpPost]
, [HttpPut]
, [HttpDelete]
, etc.
using Microsoft.AspNetCore.Mvc;
namespace MyWebApp.Controllers
{
public class ApiController : Controller
{
[HttpGet]
public IActionResult GetData()
{
return Ok(new { message = "GET request received" });
}
[HttpPost]
public IActionResult CreateData()
{
return CreatedAtAction(nameof(GetData), new { message = "POST request received" });
}
}
}
Conclusion
Controllers are the heart of your ASP.NET Core MVC application, orchestrating the flow of data and requests. Understanding how to create, configure, and use controllers effectively is crucial for building robust and maintainable web applications.