Controllers in ASP.NET Core MVC

Controllers are a core component of the Model-View-Controller (MVC) architectural pattern. In ASP.NET Core MVC, controllers are C# classes that handle incoming browser requests, interact with models to retrieve or save data, and select a view to render the response to the client.

What is a Controller?

A controller's primary responsibility is to handle user input and execute the appropriate business logic. It acts as an intermediary between the Model and the View. When a request arrives, the routing mechanism determines which controller and action method should process it.

Creating a Controller

Controllers are typically C# classes that inherit from the Controller base class provided by ASP.NET Core.


using Microsoft.AspNetCore.Mvc;

namespace MyWebApp.Controllers
{
    public class HomeController : Controller
    {
        // Action methods will go here
    }
}
        

By convention, controller classes are named using the pattern ControllerNameController (e.g., HomeController, ProductController). The base Controller class provides access to useful properties and methods, such as:

Request: Represents the incoming HTTP request. Response: Represents the outgoing HTTP response. ViewBag: A dynamic property that allows you to pass data from the controller to the view without defining a specific model class. ViewData: A dictionary that can be used to pass data to the view. Url: An object for generating URLs to actions. TempData: A dictionary that allows you to pass data between requests, typically used for redirect scenarios.

Action Methods

Action methods (or simply actions) are public methods within a controller class that handle specific requests. When a request matches a controller and an action name, the corresponding action method is executed.

Action methods must return a type derived from IActionResult. Common return types include:

Example Action Method


using Microsoft.AspNetCore.Mvc;

namespace MyWebApp.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            // Return a view named "Index" in the Views/Home folder
            return View();
        }

        public IActionResult About()
        {
            ViewBag.Message = "Your application description page.";
            return View();
        }

        public IActionResult Contact()
        {
            return View();
        }

        public IActionResult ShowDetails(int id)
        {
            // Assuming 'id' is passed from the URL or form
            ViewBag.ItemId = id;
            return View();
        }

        public IActionResult RedirectToGoogle()
        {
            return Redirect("https://www.google.com");
        }

        public IActionResult GetApiData()
        {
            var data = new { Name = "Sample Item", Value = 123 };
            return Json(data);
        }
    }
}
        

In the example above:

Routing to Controllers and Actions

ASP.NET Core uses a flexible routing system to map incoming requests to controller actions. By default, the framework looks for URLs in the format /ControllerName/ActionName/OptionalParameters.

For example:

You can customize routing extensively using attributes or the configuration in Startup.cs (or Program.cs in .NET 6+).

Convention over Configuration

ASP.NET Core heavily relies on conventions. If you name your controller ProductsController, the framework assumes the corresponding views are in the Views/Products folder. Similarly, if an action method is named List, the framework will look for a view named List.cshtml by default.

Controller Actions that Return Views

When an action method needs to render an HTML page, it typically returns a ViewResult. The View() helper method, available through the base Controller class, is used for this purpose.

Implicit and Explicit View Specification

Passing Data to Views

Controllers often need to pass data to views. ASP.NET Core MVC offers several mechanisms for this:


// Controller Action
public IActionResult UserProfile(int userId)
{
    var user = _userService.GetUserById(userId); // Assume _userService is injected

    // Using strongly-typed model (Recommended)
    return View("ProfileView", user);

    // Using ViewBag
    // ViewBag.UserName = user.Name;
    // ViewBag.UserEmail = user.Email;
    // return View();

    // Using ViewData
    // ViewData["UserName"] = user.Name;
    // ViewData["UserEmail"] = user.Email;
    // return View();
}
        

API Reference: Controller Base Class

The Microsoft.AspNetCore.Mvc.Controller class provides a rich set of functionalities for building web applications. Key members include:

For a comprehensive list, refer to the official Microsoft Learn API documentation.