ASP.NET Core Fundamentals: Controllers
Quick Answer
In ASP.NET Core, Controllers handle incoming HTTP requests, process user input, and return responses. They are central to the MVC pattern, acting as the bridge between models and views, enabling clean separation of concerns in web applications.
Learning Objectives
- Explain the purpose of Controllers in a practical learning context.
- Identify the main ideas, terms, and decisions involved in Controllers.
- Apply Controllers in a simple real-world scenario or practice task.
Introduction to ASP.NET Core Controllers
Controllers are a fundamental part of the ASP.NET Core MVC framework. They handle incoming HTTP requests, process data, and return responses to clients.
Understanding controllers is essential for building scalable and maintainable web applications using ASP.NET Core.
Controllers act as the traffic directors of your web application.
What is a Controller?
A controller in ASP.NET Core is a class that inherits from ControllerBase or Controller. It contains action methods that respond to HTTP requests.
Controllers interpret user input, interact with models, and select views or data to return as a response.
- Controllers group related action methods.
- They enable separation of concerns in MVC architecture.
- Each action method corresponds to an endpoint.
Creating a Controller
To create a controller, define a class that inherits from Controller or ControllerBase and decorate it with the [ApiController] attribute for API controllers.
Action methods are public methods that handle HTTP verbs like GET, POST, PUT, and DELETE.
- Use [HttpGet], [HttpPost], [HttpPut], [HttpDelete] attributes to specify HTTP methods.
- Action methods can return IActionResult or specific data types.
- Route attributes define URL patterns for actions.
Example: Simple Controller
Here is a basic example of a controller with a GET action method.
Routing and Controllers
Routing determines how URLs map to controller action methods. ASP.NET Core uses attribute routing or conventional routing to define these mappings.
Attribute routing uses route templates directly on controllers and actions.
- Conventional routing uses patterns defined in Startup.cs.
- Attribute routing provides fine-grained control over routes.
- Routes can include parameters to capture data from URLs.
Dependency Injection in Controllers
ASP.NET Core supports dependency injection (DI) natively. Controllers can declare dependencies in their constructors, which are automatically provided by the DI container.
This promotes loose coupling and easier testing.
- Register services in Startup.cs or Program.cs.
- Inject services via constructor parameters.
- Use interfaces to abstract dependencies.
Controller Lifecycle
Controllers are instantiated per request. After the request is processed, the controller instance is disposed.
Understanding this lifecycle helps manage resources and state appropriately.
- Controllers are short-lived objects.
- Avoid storing state in controller fields.
- Use services or session for persistent data.
Practical Example
This example defines a ProductsController with a GET action that returns a list of product names as JSON.
Examples
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet]
public IActionResult GetAll()
{
var products = new[] { "Apple", "Banana", "Cherry" };
return Ok(products);
}
}This example defines a ProductsController with a GET action that returns a list of product names as JSON.
Best Practices
- Keep controllers focused on handling HTTP requests and responses.
- Use services for business logic and data access, injected via DI.
- Use attribute routing for clear and maintainable URL patterns.
- Return appropriate IActionResult types for flexibility.
- Avoid storing state in controller instance variables.
Common Mistakes
- Putting business logic directly inside controllers.
- Not using dependency injection for services.
- Ignoring proper HTTP status codes in responses.
- Using long controller classes with many responsibilities.
- Hardcoding routes instead of using attribute routing.
Hands-on Exercise
Create a Basic Controller
Create an ASP.NET Core controller named 'BooksController' with a GET action that returns a list of book titles.
Expected output: A JSON array of book titles returned from the GET endpoint.
Hint: Use [ApiController] and [Route] attributes, and return an Ok() response with a string array.
Implement Dependency Injection
Create a service interface and implementation for retrieving data, register it in the DI container, and inject it into a controller.
Expected output: BooksController returns data from the injected service.
Hint: Define an interface IBookService with a method GetBooks(), implement it, and inject into BooksController constructor.
Interview Questions
What is the role of a controller in ASP.NET Core MVC?
InterviewA controller handles incoming HTTP requests, processes user input, interacts with models, and returns responses, acting as the intermediary between the view and the model.
How do you define an action method in a controller?
InterviewAn action method is a public method in a controller class that responds to HTTP requests, often decorated with HTTP verb attributes like [HttpGet] or [HttpPost].
How does dependency injection work in ASP.NET Core controllers?
InterviewServices are registered in the DI container and injected into controllers via constructor parameters, allowing controllers to use these services without creating them directly.
MCQ Quiz
1. What is the best first step when learning Controllers?
A. Understand the purpose and basic idea
B. Skip directly to advanced implementation
C. Ignore examples and practice
D. Memorize terms without context
Correct answer: A
Starting with the purpose and basic idea makes later examples and practice easier to understand.
2. Which activity helps reinforce Controllers?
A. Reading once without practice
B. Building or writing a small practical example
C. Avoiding review questions
D. Skipping the summary
Correct answer: B
A small practical example helps connect the topic to real usage.
3. Which statement is most accurate about this topic?
A. In ASP.NET Core, Controllers handle incoming HTTP requests, process user input, and return responses.
B. Controllers never needs examples
C. Controllers is unrelated to practical work
D. Controllers should be learned without checking results
Correct answer: A
The correct option is based on the available topic explanation.
Key Takeaways
- In ASP.NET Core, Controllers handle incoming HTTP requests, process user input, and return responses.
- They are central to the MVC pattern, acting as the bridge between models and views, enabling clean separation of concerns in web applications.
- Controllers are a fundamental part of the ASP.NET Core MVC framework.
- They handle incoming HTTP requests, process data, and return responses to clients.
- Understanding controllers is essential for building scalable and maintainable web applications using ASP.NET Core.
Summary
Controllers are essential components in ASP.NET Core MVC that handle HTTP requests and responses.
They help maintain a clean separation of concerns by delegating business logic to services and models.
Using routing, dependency injection, and proper action methods ensures scalable and maintainable web applications.
Frequently Asked Questions
What base class do controllers typically inherit from in ASP.NET Core?
Controllers typically inherit from ControllerBase or Controller, depending on whether they need view support.
Can controllers handle multiple HTTP verbs?
Yes, action methods can be decorated with attributes like [HttpGet], [HttpPost], etc., to handle specific HTTP verbs.
Is it recommended to put business logic inside controllers?
No, business logic should reside in services or models to keep controllers focused on request handling.
What is Controllers?
In ASP.NET Core, Controllers handle incoming HTTP requests, process user input, and return responses.
Why is Controllers important?
They are central to the MVC pattern, acting as the bridge between models and views, enabling clean separation of concerns in web applications.
How should I practice Controllers?
Controllers are a fundamental part of the ASP.NET Core MVC framework.

