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:

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:

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:

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 id parameter 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:

Parameter Binding

ASP.NET Core MVC automatically binds parameters from incoming requests to your action methods. This can happen through:

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.