ASP.NET Core Fundamentals

This section provides an in-depth overview of the core concepts and architectural patterns of ASP.NET Core, the cross-platform, high-performance, open-source framework for building modern, cloud-enabled applications.

What is ASP.NET Core?

ASP.NET Core is a rewrite of ASP.NET that is modular, fast, and designed for modern development practices. It allows you to build:

Key benefits include:

Core Concepts

Middleware Pipeline

ASP.NET Core uses a middleware pipeline to handle incoming HTTP requests. Each piece of middleware can:

Common middleware includes:

Example of configuring the pipeline in Program.cs:

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

Dependency Injection (DI)

ASP.NET Core has a built-in, lightweight DI container. DI is a design pattern that promotes loosely coupled code by providing dependencies to objects rather than having objects create their own dependencies.

You register services in the DI container and inject them into your application's classes (controllers, services, etc.).

Example:

// In Program.cs (or Startup.cs for older versions)
builder.Services.AddTransient<IMyService, MyService>();

// In a controller
public class HomeController : Controller
{
    private readonly IMyService _myService;

    public HomeController(IMyService myService)
    {
        _myService = myService;
    }

    public IActionResult Index()
    {
        ViewBag.Message = _myService.GetData();
        return View();
    }
}

Configuration

ASP.NET Core provides a flexible configuration system that allows you to load settings from various sources like:

The IConfiguration interface provides access to these settings.

Tip: For security-sensitive settings, use environment variables or Azure Key Vault instead of storing them directly in configuration files.

Hosting Model

ASP.NET Core applications are hosted in a WebHost. The WebHost is responsible for:

In modern ASP.NET Core (from .NET 6 onwards), the hosting model is simplified using the WebApplicationBuilder and WebApplication classes in Program.cs.

Next Steps

Now that you understand the fundamentals, explore how to build specific types of web applications: