ASP.NET Core Web API Tutorial
Lesson 5 of 100 5% of course

Controllers in ASP.NET Core Web API

1 · 6 min · 5/24/2026

Learn Controllers in ASP.NET Core Web API in our free ASP.NET Core Web API Tutorial series. Step-by-step explanations, examples, and interview tips on Toolliyo Academy.

Sign in to track progress and bookmarks.

Controllers in ASP.NET Core Web API — ShopNest.API
Article 5 of 100 · Module 1: Web API Fundamentals · Product API
Target keyword: web api controllers asp.net core · Read time: ~22 min · .NET: 8 / 9 · Project: ShopNest.API — Product API

Introduction

Controllers in ASP.NET Core Web API is essential for ASP.NET Core MVC developers building ShopNest.API — Toolliyo's 100-article enterprise learning platform covering products, orders, cart, payments, dashboard, and audit logs. Whether you target campus drives at TCS, Infosys, or Wipro, or build admin portals at product companies, this lesson delivers production-grade MVC depth.

In Indian delivery projects, teams lose sprints when juniors skip controllers fundamentals — fat controllers, missing anti-forgery tokens, or domain entities leaked to Razor views. This article prevents that class of failure on Product API.

After this article you will

  • Explain Controllers in plain English and in technical REST API terms
  • Implement controllers in ShopNest.API (Product API)
  • Compare the wrong approach vs the production-ready enterprise approach
  • Answer fresher and mid-level Web API interview questions confidently
  • Connect this lesson to Article 6 and the 100-article Web API roadmap

Prerequisites

Concept deep-dive

Level 1 — Analogy

Controllers are reception desks — they receive visitor requests, call the right department (service/model), and hand back the answer (view).

Level 2 — Technical

Controllers integrates with the ASP.NET Core Web API pipeline: register services in Program.cs, handle JSON requests in API controllers, return DTOs with correct HTTP status codes. On ShopNest.API this powers Product API without coupling UI to database internals.

Level 3 — Architecture

[Browser] → [HTTPS/Kestrel] → [Middleware Pipeline]
  → [Routing] → [Controller Action] → [Service Layer]
  → [EF Core / Identity] → [Razor View Engine] → [HTML Response]

Common misconceptions

❌ MYTH: Controllers is only needed for large enterprise apps.
✅ TRUTH: ShopNest.API starts simple — add complexity when traffic, team size, or compliance demands it.

❌ MYTH: Web API 2 and ASP.NET Core Web API are the same.
✅ TRUTH: Core Web API uses Kestrel, minimal hosting, unified pipeline with MVC — Web API 2 was separate from MVC on .NET Framework.

❌ MYTH: You can skip DTOs and return entities for internal APIs.
✅ TRUTH: Never return entities — always use DTOs, validate input, and apply authorization even on internal APIs.

Project structure

ShopNest.API/
├── Controllers/       ← HTTP request handlers
├── Models/            ← Domain entities + ViewModels
├── Views/             ← Razor .cshtml templates
├── Services/          ← Business logic (DI)
├── Data/              ← DbContext, migrations
├── Areas/Admin/       ← Admin module (Article 9+)
├── wwwroot/           ← CSS, JS, Bootstrap
└── Program.cs         ← DI + middleware pipeline

Hands-on — ShopNest.API (Product API)

Step 1 — The wrong way

// ❌ BAD — fat controller, no ViewModel, sync DB call
public IActionResult Index()
{
    return _context.Products.Find(id); // sync, exposes entity, no auth
}

Step 2 — The right way

// ✅ CORRECT — Controllers on ShopNest (Product API)
public async Task> Get(int id, CancellationToken ct)
{
    var dto = await _productService.GetDtoAsync(id, ct);
    return dto is null ? NotFound() : Ok(dto);
}

Step 3 — Apply Controllers

public class ProductsController : Controller
{
    private readonly IProductService _svc;
    public ProductsController(IProductService svc) => _svc = svc;
    public async Task<IActionResult> Index() => View(await _svc.GetAllAsync());
}
dotnet build
dotnet run --project ShopNest.API
# Verify in browser at https://localhost:5xxx

Common errors & fixes

🔴 Mistake 1: Fat controllers with EF Core queries inline
Fix: Move data access to services/repositories; keep controllers thin.

🔴 Mistake 2: Returning domain entities as JSON responses
Fix: Map entities to DTOs to prevent over-posting and data leaks.

🔴 Mistake 3: Returning domain entities directly as JSON from API
Fix: Use DTOs and AutoMapper — prevents over-posting and hides internal fields.

🔴 Mistake 4: Hard-coding connection strings in controllers
Fix: Use appsettings.json + User Secrets locally; Azure Key Vault in production.

Best practices

  • 🟢 Use async/await end-to-end for database and I/O calls
  • 🟢 Register DbContext as Scoped; avoid capturing it in singletons
  • 🟡 Use DTOs — never return EF entities directly from API endpoints
  • 🟡 Validate all input with Data Annotations or FluentValidation on DTOs
  • 🔴 Log structured data with Serilog — include OrderId, UserId, not passwords
  • 🔴 Use HTTPS, secure cookies, and authorization policies in production

Interview questions

Fresher level

Q1: What is Controllers in ASP.NET Core MVC?
A: Controllers is a core MVC capability used in ShopNest.API for Product API. Explain in one sentence, then describe controller/view/service placement.

Q2: How would you implement Controllers on a TCS-style delivery project?
A: Thin controllers, ViewModels, async EF Core, DI in Program.cs, Bootstrap 5 admin UI, and unit tests for services.

Q3: REST vs GraphQL vs gRPC — when to use which?
A: REST for CRUD and mobile/SPA backends; GraphQL for flexible client queries; gRPC for internal high-performance service calls.

Mid / senior level

Q4: Explain the Web API request lifecycle briefly.
A: Client → Kestrel → Middleware → Routing → API controller → Service/Repository → EF Core → DTO → JSON response.

Q5: Common production mistake with this topic?
A: Skipping validation, exposing secrets in Git, or untested edge cases (null model, unauthorized user).

Q6: .NET 8/9 vs .NET Framework for Web API?
A: Core is cross-platform, faster, cloud-ready; Framework is maintenance mode on Windows/IIS.

Coding round

Write a LINQ query: top 3 customers by total order value on ShopNest orders.

var top = await _context.Orders
    .GroupBy(o => o.CustomerId)
    .Select(g => new { CustomerId = g.Key, Total = g.Sum(o => o.GrandTotal) })
    .OrderByDescending(x => x.Total).Take(3).ToListAsync();

Summary & next steps

  • Article 5: Controllers in ASP.NET Core Web API
  • Module: Module 1: Web API Fundamentals · Level: BEGINNER
  • Applied to ShopNest.API — Product API

Previous: ASP.NET Core Web API Introduction — Complete Guide
Next: Routing in ASP.NET Core Web API

Practice: Add one small feature using today's pattern — commit with feat(api): article-05.

FAQ

Q1: What is Controllers?

Controllers helps ShopNest.API build maintainable Product API features using ASP.NET Core MVC 8/9 best practices.

Q2: Do I need Visual Studio?

No — .NET 8 SDK with VS Code + C# Dev Kit works. Visual Studio 2022 Community is recommended for MVC scaffolding.

Q3: Is this asked in Indian IT interviews?

Yes — MVC topics from Modules 1–6 appear in TCS, Infosys, Wipro campus drives; architecture modules in lateral hires.

Q4: Which .NET version?

Examples target .NET 8 LTS and .NET 9 with C# 12+ syntax.

Q5: How does this fit ShopNest.API?

Article 5 adds controllers to Product API. By Article 100 you have a portfolio-ready enterprise MVC app.

Test your knowledge

Quizzes linked to this course—pass to earn certificates.

Browse all quizzes
ASP.NET Core Web API Tutorial

On this page

Introduction After this article you will Prerequisites Concept deep-dive Level 1 — Analogy Level 2 — Technical Level 3 — Architecture Project structure Hands-on — ShopNest.API (Product API) Step 1 — The wrong way Step 2 — The right way Step 3 — Apply Controllers Common errors &amp; fixes Best practices Interview questions Fresher level Mid / senior level Coding round Summary &amp; next steps FAQ Q1: What is Controllers? Q2: Do I need Visual Studio? Q3: Is this asked in Indian IT interviews? Q4: Which .NET version? Q5: How does this fit ShopNest.API?
Module 1: Web API Fundamentals
What is Web API — Complete Guide REST Architecture in ASP.NET Core — Complete Guide HTTP Fundamentals for Web API Developers ASP.NET Core Web API Introduction — Complete Guide Controllers in ASP.NET Core Web API Routing in ASP.NET Core Web API HTTP Methods in ASP.NET Core Web API HTTP Status Codes in ASP.NET Core Web API Model Binding in ASP.NET Core Web API API Request Lifecycle in ASP.NET Core
Module 2: CRUD APIs
Create API in ASP.NET Core Web API Read API in ASP.NET Core Web API Update API in ASP.NET Core Web API Delete API in ASP.NET Core Web API DTOs in ASP.NET Core Web API — Complete Guide Validation in ASP.NET Core Web API Pagination in ASP.NET Core Web API Filtering in ASP.NET Core Web API Sorting in ASP.NET Core Web API Searching in ASP.NET Core Web API
Module 3: Entity Framework Core
Entity Framework Core Setup in Web API DbContext in ASP.NET Core Web API Code First with EF Core in Web API EF Core Migrations in ASP.NET Core Web API EF Core Relationships in Web API LINQ Queries with EF Core in Web API Repository Pattern in ASP.NET Core Web API Unit of Work Pattern in ASP.NET Core Web API EF Core Performance Optimization in Web API Transactions in ASP.NET Core Web API
Module 4: Authentication & Security
JWT Authentication in ASP.NET Core Web API Refresh Tokens in ASP.NET Core Web API ASP.NET Core Identity with Web API OAuth2 in ASP.NET Core Web API OpenID Connect in ASP.NET Core Web API Role-Based Authorization in Web API Claims-Based Authorization in Web API Policy-Based Authorization in ASP.NET Core Web API API Security Best Practices HTTPS and Security Headers in Web API
Module 5: Advanced APIs
API Versioning in ASP.NET Core Web API Swagger and OpenAPI in ASP.NET Core Web API Middleware in ASP.NET Core Web API Filters in ASP.NET Core Web API Global Exception Handling in Web API Logging with Serilog in Web API Rate Limiting in ASP.NET Core Web API Health Checks in ASP.NET Core Web API Caching in ASP.NET Core Web API Background Services in Web API
Module 6: Clean Architecture
Clean Architecture with ASP.NET Core Web API CQRS Pattern in ASP.NET Core Web API MediatR in ASP.NET Core Web API Repository Layer Design in Web API Service Layer Design in ASP.NET Core Web API Domain Layer in ASP.NET Core Web API Infrastructure Layer in ASP.NET Core Web API SOLID Principles in ASP.NET Core Web API Design Patterns in ASP.NET Core Web API Enterprise API Architecture — Complete Guide
Module 7: Microservices
Introduction to Microservices with ASP.NET Core API Gateway with ASP.NET Core Service Discovery in .NET Microservices Docker for ASP.NET Core Web API Docker Compose for Web API Microservices RabbitMQ with ASP.NET Core Web API MassTransit in ASP.NET Core Web API Event-Driven Architecture with Web API Distributed Transactions in Microservices Saga Pattern in ASP.NET Core Web API
Module 8: Performance & Scalability
Redis Caching in ASP.NET Core Web API Response Caching in Web API Output Caching in ASP.NET Core Web API Query Optimization in EF Core Web API Connection Pooling in ASP.NET Core Web API Async Optimization in Web API Database Indexing for Web API Performance Load Balancing for ASP.NET Core APIs Distributed Caching in Web API API Scalability — Complete Guide
Module 9: Testing
Unit Testing ASP.NET Core Web API Integration Testing in Web API Mocking with Moq in Web API Tests Postman Testing for ASP.NET Core Web API Swagger Testing in Web API Development Performance Testing for Web API Load Testing ASP.NET Core Web API API Automation Testing Test Architecture for Web API CI/CD Testing Pipeline for Web API
Module 10: Real-World Projects
Build an E-Commerce API with ASP.NET Core Build a Banking API with ASP.NET Core Web API Build a Payment Gateway API Build an HRMS API with ASP.NET Core Build a CRM API with ASP.NET Core Web API Build a Hospital Management API Build a SaaS Backend with ASP.NET Core Web API Build an Inventory API with ASP.NET Core Build a Multi-Tenant API with ASP.NET Core ShopNest.API Enterprise Microservices — Capstone Project