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.
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.
ASP.NET Core expects controller classes to end with the word Controller.
This naming convention helps the framework recognize the class as a controller.
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.
View() returns a Razor viewRedirectToAction() redirects to another actionJson() returns JSON dataContent() returns plain text or HTML contentNotFound() returns a 404 responseWhen you use the default MVC route, a URL such as:
/Home/Index
usually maps to:
HomeControllerIndex()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.
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.
Controllers are the traffic managers of your MVC application. They determine how requests are handled and what users receive in response.