Controllers are a key component of the Model-View-Controller (MVC) pattern used in ASP.NET Core MVC web applications. In this article, we will explore what controllers are, their responsibilities, and how to create and use them.
What is the Purpose of Controllers?
The core responsibility of a controller is to handle incoming HTTP requests from the browser and return a response. Controllers are responsible for interacting with the model and then selecting the appropriate view to return to the user.
In MVC, the view is only focused on displaying data and is not responsible for any business logic or data access. The model handles the actual data and business rules. The controller acts as the middleman between the view and model, processing requests and returning responses.
An ASP.NET Core Development Company focuses on developing controllers as a key part of building the application architecture in ASP.NET Core MVC projects. The controllers process incoming requests and coordinate between Models and Views, serving as the central hub for routing and overall app workflow. Experienced ASP.NET Core developers understand the critical role of controllers and implement them properly according to best practices.
Some key things controllers do include:
- Handle HTTP requests and responses
- Perform validation on
- incoming data Interact with the model to retrieve or manipulate data
- Select which view to return based on the request
- Handle errors and exceptions
By separating this processing logic from the view, it keeps views focused purely on display and allows the underlying business logic and data access to be easily modified without impacting how the UI is rendered.
Core Functionality of ASP.NET Core Controllers
At its core, each ASP.NET Core controller class must inherit from the Controller base class. This provides a number of functions and attributes that allow the class to handle requests and responses:
- Action methods – Define methods on the controller to handle specific requests. These methods must be public and return an IActionResult.
- Http verbs – Actions are mapped to HTTP verbs like GET, POST, PUT, DELETE using attributes.
- Route templates – Actions are linked to URL patterns using attributes to define routes.
- Model binding – Action parameters can bind to complex model objects automatically from request data.
- Action results – Methods can return different result types like views, JSON, and redirects. Dependency injection – Services and contexts can be easily injected via constructors for data access.
- Filters – Attributes allow code to run before/after actions for things like auth checks.
So in summary, controllers provide a clean class-based way to handle routing, request processing, model binding, results and dependency injection in ASP.NET Core MVC apps.
Creating Controller Classes
When setting up a new ASP.NET Core MVC project, template code will already include the basic HomeController class that handles default index and about action methods.
To create additional controllers, right click on the Controllers folder in Solution Explorer and select Add > Controller. This will scaffold a new Controller class file and add it to the Controllers folder.
The generated controller class will inherit from ControllerBase and include some template code and comments to get started. Properties and constructor code can be added to inject dependencies.
Action methods should be public with return types of IActionResult, Task<IActionResult> or specific result types like ViewResult. Method names are used to determine the request URL route by default.
Additionally, attributes like HttpGet and HttpPost can be added to associate actions with specific HTTP verbs. Route and RoutePrefix attributes customise URL mappings.
So in summary – new controllers are simple classes inheriting from ControllerBase with public action methods mapped to routes and verbs via attributes.
Routing and Action Methods
Routing is how controller actions get mapped to specific URLs. ASP.NET Core uses attribute routing by default which decorates actions with attributes like Route and Http verb.
For example, a basic action could look like:
This maps the GET /products URL to the Index action method.
Route templates allow capturing route segments as parameters like:
The {id} segment is bound to the id parameter.
Actions can also specify custom routes:
And RoutePrefix sets a common base path for multiple actions.
Beyond basic routing, filters enable preprocessing logic via attributes. Authentication and authorization filters ensure users are authorized. Exception filters handle exceptions gracefully.
Model Binding
A core feature of ASP.NET Core MVC is model binding – automatically mapping incoming request data to action method parameters.
For example, a POST method to create a product:
The Product model is instantiated and bound to form fields automatically.
Complex types are handled as well via the [FromBody] attribute for JSON/XML requests.
Model state validation also allows validating models and returning errors.
With model binding, action methods can focus on business logic rather than request parsing.
Action Results
Controller actions often need to send a response after processing a request. The return type IActionResult represents different response types.
Common result types include:
- ViewResult – Returns a view from the Views folder.
- JsonResult – Serializes an object to JSON.
- RedirectResult – Redirects to another action or URL.
For example:
Developers are also free to create their own result types that inherit from IActionResult.
Results handle returning views and data while separating presentation from business logic.
Dependency Injection
An important feature of ASP.NET Core is dependency injection (DI) which is used to resolve dependencies and supply them to classes.
Controllers take advantage of DI by declaring dependencies via constructor parameters:
Then services can be injected and used throughout the class.
This avoids direct newing up dependencies and leads to cleaner, more testable code. The service lifetime scopes are managed externally as well.
Common dependencies injected into controllers include DbContexts, repositories, APIs, etc. DI enables easy mocking in unit tests too.
Summary
In summary, controllers are at the core of ASP.NET Core MVC and handle:
- Routing requests to actions
- Model binding request data
- Interacting with services via DI
- Selecting result types
- Separating presentation from logic
By adhering to the MVC pattern, controllers allow building robust, scalable web apps by keeping business logic decoupled from UI code. Attributes provide a clean syntax to map routes, bind models and handle requests/responses. Overall, controllers are a fundamental piece enabling the full MVC framework in ASP.NET Core.
Hire ASP.NET Core Developers to properly implement controllers that serve as the central hub of ASP.NET Core MVC apps. Experienced .NET developers understand how controllers fit into the overall MVC architecture and coordinate between models, views and routes. They know how to leverage attributes to clean route mapping and model binding, allowing apps to focus on core logic rather than low-level request handling. Engaging with ASP.NET experts ensures controllers are developed optimally to drive scalable and maintainable application workflow.