ASP.NET Core Basics
ASP.NET Core is a modern, cross-platform, high-performance framework for building cloud-enabled, internet-connected applications like web apps, IoT apps, and mobile backends.
1. The Middleware Pipeline
At its core, ASP.NET Core is a pipeline of components called Middlewares. When a request comes in, it passes through these components one by one. Each middleware can:
- Pass the request to the next middleware in the pipeline.
- Perform work before and after the next middleware is invoked.
- Short-circuit the request (stop it from going further).
var app = builder.Build();
// Middleware examples
app.UseHttpsRedirection(); // Force HTTPS
app.UseStaticFiles(); // Serve CSS/JS/Images
app.UseRouting(); // Find the right controller
app.UseAuthentication(); // Who is this?
app.UseAuthorization(); // Are they allowed?
app.MapControllers(); // Final destination
2. Dependency Injection (DI)
ASP.NET Core is designed from the ground up to support Dependency Injection. This pattern allows you to write loosely coupled, testable code by "injecting" services into controllers or other classes.
Service Lifetimes
When you register a service, you must choose how long it lives:
- Transient: A new instance is created every time it is requested.
- Scoped: A new instance is created once per HTTP request. (Ideal for Database Contexts).
- Singleton: A single instance is created the first time it's requested and shared across the entire app until it shuts down.
// Program.cs
builder.Services.AddTransient<IMyService, MyService>();
builder.Services.AddScoped<IRepository, SqlRepository>();
builder.Services.AddSingleton<ICache, MemoryCache>();
3. Routing: Mapping URLs to Code
Routing is the process of matching an incoming HTTP request to a specific Action inside a Controller.
Attribute Routing (Preferred for APIs)
You define the route directly on the controller or action using [Route].
[ApiController]
[Route("api/[controller]")] // e.g., api/products
public class ProductsController : ControllerBase
{
[HttpGet("{id}")] // e.g., GET api/products/5
public IActionResult GetProduct(int id) { ... }
}
4. Web APIs vs. MVC
Web APIs (Data-Centric)
Used for building backends that return Data (usually JSON). They are the foundation for modern Single Page Applications (React, Angular, Vue) and Mobile Apps.
- Inherits from
ControllerBase. - Uses
[ApiController]attribute. - Returns
ActionResult<T>orIActionResult.
MVC: Model-View-Controller (UI-Centric)
Used for building web applications that return HTML (Server-Side Rendering).
- Model: The data and business logic.
- View: The UI (Razor
.cshtmlfiles) that displays the data. - Controller: The brain that handles user input and connects the Model to the View.
5. Building a Web API Controller
A typical API controller uses Attributes to define its behavior.
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly IUserService _userService;
// Dependency Injection in action
public UsersController(IUserService userService)
{
_userService = userService;
}
[HttpGet] // GET /api/users
public async Task<IActionResult> GetAll()
{
var users = await _userService.GetUsersAsync();
return Ok(users); // Returns 200 OK with JSON data
}
[HttpPost] // POST /api/users
public async Task<IActionResult> Create([FromBody] UserDto user)
{
if (!ModelState.IsValid) return BadRequest();
var created = await _userService.AddUserAsync(user);
return CreatedAtAction(nameof(GetAll), new { id = created.Id }, created);
}
}
6. Model Binding & Validation
ASP.NET Core automatically maps data from the HTTP request (Query string, Route, or Body) to your action parameters. This is called Model Binding.
You can use Data Annotations for automatic validation:
public class UserDto
{
[Required]
[EmailAddress]
public string Email { get; set; }
[MinLength(8)]
public string Password { get; set; }
}
If the validation fails, the [ApiController] attribute automatically returns a 400 Bad Request before your code even runs.