ASP.NET Core Fundamentals
This section covers the core concepts and architecture of ASP.NET Core, enabling you to build robust and scalable web applications.
Table of Contents
- Introduction to ASP.NET Core
- Middleware Pipeline
- Dependency Injection
- Configuration
- Routing
- Hosting
- Models, Views, and Controllers (MVC)
- Razor Pages
Introduction to ASP.NET Core
ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-based, Internet-connected applications. It's a rewrite of ASP.NET and combines the best features of ASP.NET, MVC, Web API, and SignalR into a single, unified framework.
Key benefits include:
- Cross-Platform: Run on Windows, macOS, and Linux.
- High Performance: Optimized for speed and efficiency.
- Modern Tooling: Integrates with Visual Studio, VS Code, and command-line tools.
- Modular Design: Build applications with only the components you need.
Middleware Pipeline
ASP.NET Core applications process HTTP requests through a pipeline of middleware components. Each middleware component can:
- Execute code before the next component in the pipeline.
- Short-circuit the request pipeline by returning a response early.
- Delegate execution to the next component in the pipeline.
- Optionally, execute code after the next component is executed.
The order of middleware in the pipeline is critical, as it determines the order in which requests are processed.
Common middleware includes:
UseRouting()
: Enables routing capabilities.UseAuthentication()
: Handles authentication.UseAuthorization()
: Handles authorization.UseEndpoints()
: Executes endpoint handlers.
public void Configure(IApplicationBuilder app)
{
app.UseRouting();
app.UseStaticFiles(); // Example middleware
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context => await context.Response.WriteAsync("Hello, World!"));
});
}
Dependency Injection
ASP.NET Core has a built-in, first-party support for Dependency Injection (DI). DI is a design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. It makes code more maintainable, testable, and loosely coupled.
The DI container manages the lifecycle of services and injects them into constructors or properties of consuming classes.
Startup.cs
(or Program.cs
in .NET 6+).
// In Startup.cs or Program.cs
services.AddScoped<IMyService, MyService>();
// In a controller or service
public class MyController : Controller
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
// ...
}
Configuration
ASP.NET Core's configuration system is flexible and supports multiple configuration sources, allowing you to manage application settings from various locations.
Supported sources include:
- JSON files (e.g.,
appsettings.json
) - Environment variables
- Command-line arguments
- Azure Key Vault
- Custom providers
Configuration values can be accessed via the IConfiguration
interface.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
var builder = WebApplication.CreateBuilder(args);
// Accessing configuration
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
var logLevel = builder.Configuration["Logging:LogLevel:Default"];
// ...
}
appsettings.json
is loaded. You can also have environment-specific configuration files like appsettings.Development.json
.
Routing
Routing maps incoming HTTP requests to specific handler methods in your application. ASP.NET Core supports attribute-based routing and convention-based routing.
Attribute Routing: Define routes directly on controller actions or Razor Page handlers using attributes like [Route]
and [HttpGet]
.
public class ProductsController : Controller
{
[HttpGet("api/products/{id}")]
public IActionResult GetProduct(int id)
{
// ...
}
}
Convention-Based Routing: Define routes in the Startup.cs
(or Program.cs
) file using the MapControllerRoute
or MapRazorPages
methods.
// In Startup.cs or Program.cs
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
Hosting
ASP.NET Core applications can be hosted in various environments, including IIS, Kestrel (built-in web server), Nginx, Apache, and Docker containers.
Kestrel: Kestrel is a cross-platform web server included with ASP.NET Core. It's lightweight and can be used standalone or behind a reverse proxy like Nginx or IIS.
IIS/Nginx: For production environments, it's common to use a reverse proxy to handle SSL termination, load balancing, and serving static files.
The Program.cs
file (or Startup.cs
in older versions) is where the web host is configured and started.
Models, Views, and Controllers (MVC)
The Model-View-Controller (MVC) architectural pattern separates an application into three interconnected components:
- Model: Represents the data and business logic of the application.
- View: Responsible for presenting the data to the user, typically using Razor syntax.
- Controller: Handles user input, interacts with the Model, and selects a View to render.
MVC is well-suited for complex, data-driven applications.
Razor Pages
Razor Pages is a page-focused model for building web UI with ASP.NET Core. It simplifies building inline HTML with server-side code, making it easier to create dynamic web pages.
Each Razor Page consists of:
- A
.cshtml
file for the HTML markup. - A code-behind file (e.g.,
.cshtml.cs
) that contains the page logic and properties.
Razor Pages are ideal for simpler scenarios or when you want a more direct page-centric approach.