← Back to ASP.NET Core Tutorial Home

Lesson 7: Understanding Controllers

Controllers are one of the most important parts of an ASP.NET Core MVC application. They receive browser requests, process logic, and decide what response should be returned.

What a controller does

Example of a simple controller

using Microsoft.AspNetCore.Mvc;

public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

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

In this example, HomeController has two action methods: Index() and About(). Each action typically corresponds to a page or endpoint.

Why the name ends with Controller

ASP.NET Core expects controller classes to end with the word Controller. This naming convention helps the framework recognize the class as a controller.

Action methods

Each public method inside a controller is called an action method. An action method usually returns an IActionResult, which allows flexibility in the type of response.

Routing and controllers

When you use the default MVC route, a URL such as:

/Home/Index

usually maps to:

Returning a view with data

Controllers can also pass data to views. For example:

public IActionResult Welcome()
{
    ViewBag.Message = "Welcome to ASP.NET Core";
    return View();
}

The view can then display the message to the user.

Controllers should stay focused

A controller should coordinate requests and responses, but it should not contain too much business logic. In larger applications, business rules are often placed in service classes instead of inside controllers.

Best practice: Keep controllers thin and focused on request handling.

Conclusion

Controllers are the traffic managers of your MVC application. They determine how requests are handled and what users receive in response.

← Previous Lesson Next Lesson: Working with Views →