Controllers and Actions in ASP.NET Core
In ASP.NET Core MVC, controllers are fundamental to handling incoming browser requests and processing them. They act as the central hub, coordinating the request processing and returning a response. Actions are methods within a controller that are executed in response to specific routes.
What are Controllers?
A controller is a class that inherits from Controller or ControllerBase. It contains public methods, called actions, that handle HTTP requests. Controllers are responsible for:
- Receiving request data.
- Interacting with model objects to retrieve or persist data.
- Selecting a view to render the response.
- Returning different types of responses (e.g., HTML, JSON, redirects).
What are Actions?
Actions are public methods within a controller. When a request matches a route that points to a specific controller and action, that action method is invoked. Key characteristics of actions include:
- They must be public methods.
- They can return various types, such as
IActionResult,string,ViewResult,JsonResult,RedirectResult, etc. - Parameters can be bound directly from the request URL, query string, or form data.
Creating a Controller and Actions
Let's create a simple controller named HomeController with a couple of actions.
1. Create the Controller File:
In your ASP.NET Core project, navigate to the Controllers folder and create a new C# file named HomeController.cs.
using Microsoft.AspNetCore.Mvc;
namespace YourProjectName.Controllers
{
public class HomeController : Controller
{
// Action to handle the homepage request
public IActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET Core MVC!";
return View(); // Renders the Index.cshtml view
}
// Action to display a greeting
public IActionResult Greet(string name)
{
if (string.IsNullOrEmpty(name))
{
name = "Guest";
}
ViewData["Greeting"] = $"Hello, {name}!";
return View("Greeting"); // Renders the Greeting.cshtml view
}
// Action that returns plain text
public string Status()
{
return "The server is running.";
}
}
}
2. Create Corresponding Views (Optional):
Create Razor views in the Views/Home folder:
Views/Home/Index.cshtml:
@{
ViewData["Title"] = "Home Page";
}
<h1>@ViewData["Message"]</h1>
<p>Explore our features and learn more about ASP.NET Core.</p>
<p>
<a href="@Url.Action("Greet", "Home")">Say Hello</a> |
<a href="@Url.Action("Greet", "Home", new { name = "Developer" })">Say Hello to Developer</a> |
<a href="@Url.Action("Status", "Home")">Server Status</a>
</p>
Views/Home/Greeting.cshtml:
@{
ViewData["Title"] = "Greeting";
}
<h2>@ViewData["Greeting"]</h2>
<p><a href="/">Back to Home</a></p>
Note: The Status() action doesn't explicitly return a view. By returning a simple string, it sends plain text directly to the browser.
Routing to Controllers and Actions
ASP.NET Core uses a sophisticated routing system to map incoming requests to the correct controller actions. By default, the routing convention follows the pattern:
/ControllerName/ActionName/OptionalParameters
For our HomeController:
- A request to
/Home/Index(or just/ifIndexis the default action andHomeis the default controller) will execute theIndex()action. - A request to
/Home/Greetwill execute theGreet()action withnamebeing null or empty. - A request to
/Home/Greet?name=Alicewill execute theGreet()action withnameset to "Alice". - A request to
/Home/Statuswill execute theStatus()action and return the string "The server is running.".
Default Routing
In many ASP.NET Core MVC applications, the Program.cs (or Startup.cs in older versions) file configures the default route. Typically, it looks something like this:
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
This means:
- If no controller is specified, use
Home. - If no action is specified, use
Index. - An optional
idparameter can be passed.
Action Results
IActionResult is an interface that represents the result of an action method. It allows controllers to return various types of HTTP responses. Common implementations include:
ViewResult: Returns an HTML view.JsonResult: Returns data in JSON format, often used for APIs.RedirectResult: Redirects the browser to another URL.ContentResult: Returns plain text or HTML.NotFoundResult: Returns an HTTP 404 Not Found status.OkResult: Returns an HTTP 200 OK status.
Parameter Binding
ASP.NET Core MVC automatically binds parameters from incoming requests to your action methods. This can happen through:
- Route Data: Values defined in the URL pattern (e.g.,
/Products/Details/5where 5 is the ID). - Query String: Values from the URL's query string (e.g.,
/Search?query=mvc). - Form Body: Values submitted via an HTML form.
- HTTP Headers: Values from request headers.
You can use the [FromRoute], [FromQuery], [FromBody], and [FromHeader] attributes to explicitly specify where a parameter should be bound from.
Tip
For API controllers, you'll typically use ControllerBase instead of Controller and return data types directly or use IStatusCodeActionResult for status codes.
Summary
Controllers and actions are the backbone of the Model-View-Controller (MVC) pattern in ASP.NET Core. They provide a structured way to handle user input, process data, and deliver dynamic web content or API responses. By understanding how to create and configure them, you can build robust and scalable web applications.