Microsoft.AspNetCore.Mvc

Namespace for ASP.NET Core MVC components, enabling the creation of powerful, data-driven applications using the Model-View-Controller pattern.

Core Concepts

The Microsoft.AspNetCore.Mvc namespace provides the building blocks for developing web applications with ASP.NET Core that follow the MVC architectural pattern. This includes controllers, actions, views, models, routing, and model binding.

Controllers

Controllers are responsible for handling incoming HTTP requests, processing them, and returning responses. They act as the entry point for your application's logic.

public abstract class Controller : IDisposable

Key features of controllers include:

Actions

Action methods are the specific functions within a controller that handle a particular request. They are typically public methods that return an IActionResult.

public virtual Task<IActionResult> YourActionMethod(...)

Common IActionResult implementations include:

Views

Views are responsible for presenting data to the user, typically as HTML. They are often created using Razor syntax (.cshtml files).

Model Binding and Validation

ASP.NET Core MVC automatically binds incoming request data to your controller action parameters. You can also apply validation attributes to your models to ensure data integrity.

Note: Model binding can be customized using attributes like [BindProperty] or by implementing custom model binders.

Routing

The routing system maps incoming URL requests to specific action methods in your controllers. Convention-based routing and attribute routing are supported.

Key Classes and Interfaces

Example: A Simple API Controller

Here's a basic example of an API controller that returns a list of items:


using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        var products = new List<string> { "Laptop", "Keyboard", "Mouse" };
        return Ok(products);
    }

    [HttpGet("{id}")]
    public ActionResult<string> Get(int id)
    {
        if (id == 1)
        {
            return Ok("Laptop");
        }
        return NotFound();
    }
}
        

Important: When building APIs, consider using ControllerBase instead of Controller to avoid unnecessary view-related features.