Search⌘ K
AI Features

Controllers and Actions

Explore the role of controllers in ASP.NET Core MVC, including how they interpret routes, execute action methods, and return views or data to clients. Understand the importance of keeping controllers thin and delegating business logic to services, enabling you to build scalable and organized web applications.

In MVC, the C stands for the controller. From the route and an incoming URL, ASP.NET Core knows the name of the controller, so it will then look for a class that is decorated with the [Controller] attribute or derives from a class decorated with that attribute, for example, the Microsoft-provided class named ControllerBase, as shown in the following code:

C#
namespace Microsoft.AspNetCore.Mvc
{
//
// Summary:
// A base class for an MVC controller without view support.
[Controller]
public abstract class ControllerBase
{
...

The ControllerBase class

As we can see in the XML comment, ControllerBase does not support views. It is used for creating web services, as seen in the Building and Consuming Web Services. ControllerBase has many useful properties for working with the current HTTP context, as shown in the following table:

Property

Description

Request

Just the HTTP request. For example, headers, query string parameters, the body of the request as a stream that you can read from, the content type and length, and cookies.


Response

Just the HTTP response. For example, headers, the body of the response as a stream that you can write to, the content type and length, status code, and cookies. There are also delegates like OnStarting and OnCompleted that you can hook a method up to.


HttpContext

Everything about the current HTTP context including the request and response, information about the connection, a collection of features that have been enabled on the server with middleware, and a User object for authentication and authorization.

...