Controllers in ASP.NET

Learn about controller classes and their action methods in ASP.NET Core.

Controller classes are where your application logic resides. At the end of this lesson, the entire controller is written in the code widget. Look at the code line by line to figure out how it is functioning.

Controller inheritance

public class UsersController : Controller

ASP.NET requires every controller class to implement the IController interface. The Controller class implements that interface while also providing you support for views. As a result, you inherit Controller into your UserController class.

Dependency injection

Press + to interact
private readonly UsersContext _context;
public UsersController(UsersContext context)
{
_context = context;
}

ASP.NET Core utilizes dependency injection to establish a relationship between controllers and your database context. Specifically, it uses constructor injection. This allows you to use _context throughout your controller class to access your database without having to initialize any object.

In your application, you have named your database context as UsersContext. You can explore its code by going to Data > UsersContext.cs in the code widget at the end of this lesson.

Action methods

In ASP.NET, methods inside a controller are called “action methods”. The name of an action method is also used to map its URL endpoint. For example, if the controller name is UserController and the name of an action method is Details, then there is a URL endpoint ...