ASP.NET Core Fundamentals
ASP.NET Core is a modern, cross-platform, open-source framework for building internet-connected applications. This guide covers the foundational concepts you need to get started.
What is ASP.NET Core?
ASP.NET Core is a high-performance, extensible, and modern web framework designed for building:
- Web applications
- Web APIs
- Real-time applications (e.g., SignalR)
- Microservices
It's a complete rewrite of ASP.NET, offering significant improvements in performance, development experience, and flexibility. It runs on .NET, which includes .NET 5, .NET 6, .NET 7, and .NET 8.
Key Concepts
1. Middleware Pipeline
ASP.NET Core uses a middleware pipeline to handle HTTP requests. Each piece of middleware can:
- Execute code before the next middleware.
- Short-circuit the request (e.g., for authentication).
- Call the next middleware in the pipeline.
- Execute code after the next middleware.
Common middleware includes:
- Routing: Matches incoming requests to endpoints.
- Authentication: Verifies the user's identity.
- Authorization: Checks if the authenticated user has permission to access a resource.
- Static Files: Serves static content like HTML, CSS, and JavaScript.
- Endpoint Execution: Invokes the handler for the matched endpoint.
You configure the pipeline in the Program.cs
file:
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(); // Or app.MapControllers(); for MVC/API
app.Run();
2. Dependency Injection (DI)
ASP.NET Core has a built-in, first-party DI container. DI is a design pattern used to achieve Inversion of Control (IoC) and loosely coupled code.
Services can be registered with the container in Program.cs
using various lifetimes:
- Transient: A new instance is created every time it's requested.
- Scoped: A single instance is created per client request.
- Singleton: A single instance is created for the application's lifetime.
Example of registering and injecting a service:
// Program.cs
builder.Services.AddScoped<IMyService, MyService>();
// In your controller or page model
public class MyController : Controller
{
private readonly IMyService _myService;
public MyController(IMyService myService)
{
_myService = myService;
}
// ... controller actions
}
public interface IMyService { }
public class MyService : IMyService { }
3. Hosting and Configuration
The WebApplication.CreateBuilder()
method sets up a host that manages the lifecycle of your application, including:
- Configuration loading (from JSON files, environment variables, command-line arguments, etc.).
- Logging setup.
- Dependency Injection container.
- Kestrel web server.
Configuration values can be accessed via the IConfiguration
object.
// Program.cs
var configuration = builder.Configuration;
string connectionString = configuration.GetConnectionString("DefaultConnection");
string logLevel = configuration["Logging:LogLevel:Default"];
4. Request Delegates (Middleware)
The core of the ASP.NET Core pipeline is a series of delegates that process the HTTP request. Each delegate can:
- Perform an action.
- Pass the request to the next delegate.
- Not pass the request forward (short-circuit).
You can write your own custom middleware.
// Custom Middleware Example
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
context.Response.Headers.Add("X-Custom-Header", "Hello from Middleware!");
await _next(context); // Pass control to the next middleware
}
}
// In Program.cs
app.UseMiddleware<CustomMiddleware>();
Next Steps
Explore these related topics to deepen your understanding:
- ASP.NET Core MVC
- ASP.NET Core Razor Pages
- ASP.NET Core Web APIs
- Entity Framework Core
- SignalR for Real-time Web Functionality