ASP.NET Core Fundamentals
This section provides a foundational understanding of ASP.NET Core, its architecture, and core concepts. ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, internet-connected applications.
Key Concepts
What is ASP.NET Core?
ASP.NET Core is a rewrite of the ASP.NET platform. It's designed to be modular, light-weight, and highly performant. It enables the development of:
- Web applications
- IoT applications
- Mobile backends
- APIs
It can run on Windows, macOS, and Linux.
Middleware Pipeline
At the heart of ASP.NET Core's request processing is the middleware pipeline. Each piece of middleware in the pipeline has the opportunity to:
- Execute code before the request is passed to the next middleware.
- Short-circuit the request, preventing it from being passed further down the pipeline.
- Call the next middleware in the pipeline.
- Execute code after the next middleware has completed.
Common middleware includes:
- Static File Middleware
- Routing Middleware
- Authentication Middleware
- Authorization Middleware
- MVC/Razor Page Middleware
Dependency Injection
ASP.NET Core has a built-in, first-class support for Dependency Injection (DI). DI is a design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. In ASP.NET Core, the DI container is integrated into the framework:
// Example of registering a service
services.AddScoped<IMyService, MyService>();
// Example of injecting a service into a controller
public class MyController : Controller
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
public IActionResult Index()
{
_myService.DoSomething();
return View();
}
}
Configuration
ASP.NET Core provides a flexible configuration system that allows you to load settings from various sources, including JSON files, environment variables, command-line arguments, and Azure Key Vault. The configuration system is built around the IConfiguration
interface.
// Accessing configuration in Startup.cs
public void ConfigureServices(IServiceCollection services)
{
var configValue = Configuration["MySetting"];
services.AddSingleton<IOptions<MySettings>>(
new Options<MySettings>(Configuration.GetSection("MySettings").Get<MySettings>()));
}
Hosting Model
ASP.NET Core applications are hosted using an IHost
. The host is responsible for:
- Server configuration (e.g., Kestrel)
- Middleware pipeline configuration
- Dependency injection container setup
- Background service execution
The Program.cs
file typically sets up and runs the host.
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
Next Steps
Explore related documentation: