ASP.NET Core MVC Beginner

Controllers and actions

Controllers group the code that handles requests, and each public method on a controller is an action. This lesson shows how MVC finds controllers, what action methods can return, and the helper methods that make returning views, redirects and errors short and clear.

What happens when an action runs
  1. StartRoute matchedRouting picks ProductsController and its Details action
  2. Step 2Controller createdA new instance per request, with services from DI
  3. Step 3Parameters boundModel binding fills id from the URL
  4. Step 4Action runsYour code loads data and decides what to return
  5. Step 5IActionResult returnedView, RedirectToAction, NotFound, Json and so on
  6. EndResult executedMVC turns the result into the HTTP response

The idea in plain words

A controller is a class that groups related request handlers. A ProductsController might handle listing products, showing one product and saving a new one. Each of those handlers is a public method called an action. When routing matches a URL, MVC creates the controller, calls the action, and turns whatever the action returns into an HTTP response.

Controllers are created fresh for every request, so you should not store per-user data in controller fields. Anything the controller needs, such as a database context or a service, comes in through the constructor using dependency injection.

How MVC finds controllers

By convention a class is treated as a controller when it is public, not abstract, and either its name ends with Controller or it inherits from a class whose name ends with Controller. You can also mark a class with the [Controller] attribute. In practice almost every MVC controller inherits from the Controller base class, which gives you helper methods for views, redirects and status codes.

Every public method on a controller is an action unless you mark it with [NonAction]. That means helper methods should be private, otherwise they could be reached from a URL.

  • Inherit from Controller for MVC apps that return views.
  • Inherit from ControllerBase for API-only controllers; it has no view helpers.
  • Keep helper methods private or mark them [NonAction].

What an action can return

Most actions return IActionResult, an interface for any result that knows how to write a response. The Controller base class has short helper methods that create these results for you. Choosing the right helper is what decides the status code and body the browser receives.

  • View() or View(model): renders a Razor view and returns 200.
  • RedirectToAction("Index"): sends a 302 redirect to another action.
  • NotFound(): returns 404 when the requested item does not exist.
  • BadRequest(): returns 400 when the input is invalid.
  • Json(data) or Ok(data): returns data, commonly as JSON.

Example

The controller below gets its data service through the constructor, returns 404 when a product is missing, and follows the Post-Redirect-Get pattern after saving, so a browser refresh does not submit the form twice.

C#
public class ProductsController : Controller
{
    private readonly IProductService _products;

    public ProductsController(IProductService products)
    {
        _products = products;
    }

    // GET /products
    public async Task<IActionResult> Index()
    {
        var items = await _products.GetAllAsync();
        return View(items);
    }

    // GET /products/details/5
    public async Task<IActionResult> Details(int id)
    {
        var product = await _products.FindAsync(id);
        if (product is null)
        {
            return NotFound();
        }
        return View(product);
    }

    // POST /products/create
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create(Product product)
    {
        if (!ModelState.IsValid)
        {
            return View(product); // show the form again with errors
        }
        await _products.AddAsync(product);
        return RedirectToAction(nameof(Index));
    }
}

In Visual Studio 2026

You rarely type a controller from scratch. Right-click the Controllers folder, choose Add, then Controller, and pick MVC Controller - Empty for a blank class, or MVC Controller with read/write actions for Index, Details, Create, Edit and Delete stubs. Put a breakpoint in an action (click in the left margin or press F9), press F5, open the page in the browser, and Visual Studio stops on that line so you can inspect parameters.

Common mistakes

These issues show up again and again in code reviews of beginner MVC projects.

  • Leaving a helper method public, which quietly turns it into a reachable action.
  • Returning View() after a successful POST instead of redirecting, so refreshing the page resubmits the form.
  • Using magic strings like RedirectToAction("Index") everywhere; nameof(Index) survives renames.
  • Blocking on async code with .Result or .Wait(). Make the action async and await the call.
  • Storing request data in controller fields and expecting it to survive to the next request.

Going further

Actions can also return a specific type such as Product, or ActionResult<Product> to combine a typed result with status helpers, which is most useful in API controllers. Attributes like [HttpGet], [HttpPost] and [Route] control which requests reach an action, and filters let you run code before and after actions. Those topics come later in this course.

Here is the same lookup written for an API controller. ControllerBase has no view helpers, and ActionResult<Product> lets the action return either the product, serialized as JSON, or a status result such as NotFound.

C#
[ApiController]
[Route("api/products")]
public class ProductsApiController : ControllerBase
{
    private readonly IProductService _products;

    public ProductsApiController(IProductService products) => _products = products;

    // GET /api/products/5
    [HttpGet("{id:int}")]
    public async Task<ActionResult<Product>> Get(int id)
    {
        var product = await _products.FindAsync(id);
        return product is null ? NotFound() : product;
    }
}

Interview question

What is the difference between inheriting from Controller and from ControllerBase?

ControllerBase provides what a controller needs to handle HTTP requests, such as ModelState, Ok, NotFound and BadRequest. Controller inherits from ControllerBase and adds support for views, including View, PartialView, ViewBag, ViewData and TempData. Use Controller for MVC apps that render pages and ControllerBase for API-only controllers.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.